PowerShell Fundamentals

View this project on GitHub

PowerShell is a powerful command-line shell and scripting language built on .NET and .Core Frameworks depending on the version. Designed for system administrators and power users, it automates repetitive tasks, manages system configurations, and interacts with APIs, registry, and file systems. It is object-based (unlike traditional text-based shells), meaning it passes objects between commands (not just raw text), which gives it unique flexibility.


Getting Started with PowerShell



.NET and .Core Frameworks

.NET Framework

The .NET Framework is the core powerhouse behind PowerShell's intelligence. It's not just a programming platform - it's the engine that gives PowerShell its ability to work with complex data, interact with the Windows operating system, and control almost every part of your system with precision. When you run a cmdlet like Get-Process or manipulate objects with Select-Object, you're tapping directly into the .NET 's rich library of pre-built classes and methods.

In simple terms, the .NET Framework provides PowerShell with:

PowerShell isn't just a shell - it's a scripting language deeply rooted in the .NET ecosystem, which is why it can do far more than traditional shells. Every command you run inherits the depth and structure of .NET, turning simple commands into powerful, scalable automation scripts.


.Core Framework

The .NET Core Framework is the modern, cross-platform foundation behind PowerShell Core's flexibility and reach.

Unlike the tradtional .NET Framework, which is Windows-specific, the .NET Core is designed more for portability, allowing PowerShell Core to be cross-platform (Windows, Linux, macOS). It's modular, lightweight, and fast. It's built to meet the demands of modern automation.

The .NET Core Framework provides PowerShell Core with:

PowerShell Core is a foward-looking scripting solution that is built on the .NET Core foundation. Often used for diverse tasks such as managing servers, deploying containers, or scripting across different platforms, PowerShell Core with .NET Core brings the power of .NET to modern automation.





Windows PowerShell and PowerShell Core

The differences between Windows PowerShell and PowerShell Core lie within platform support, runtime, and development direction.

Platform and Version

Windows PowerShell

Features:

PowerShell Core

Features:





Cmdlets & Basic Syntax and structure

Cmdlet = Command + Let (lightweight commands)

Cmdlets are the precision tools of PowerShell - small but powerful commands that do one job and do it well. Cmdlets can be thought of as individual building blocks in a high performance automation toolkit. Written in the .NET Framework and designed specifically for administrative tasks, each cmdlet follows a clear Verb-Noun format, making it easy to guess and intuitive to learn. Unlike traditional shell commands that output plain text, cmdlets output structured objects, allowing you to filter, sort, and manipulate data with accuracy. Whether you're pulling system info, managing users, or stopping rogue services, cmdlets are your go-to tools for scripting control and operational mastery.

Naming Format

Cmdlets use a Verb-Noun naming pattern for clarity and consistency:

Verb Noun Meaning
Get- Help Displays help info about cmdlets
Get- Command Lists available cmdlets
Get- Process Show running processes
Get- Service Show running services
Start- Service Start a specific service
Restart- Service Restart a specific service
Stop- Service Stop a specific service
GetHelp.png GetCommand.png GetProcess.png GetService.png ServiceMgmt.png



Exploration


            $PSVersion
            Get-Module -ListAvailable
            Get-Command -Module ModuleName
            List Command -Module ModuleName
            Get-FileHash
            Get-FileHash -Algorithm SHA1 path
            NetAdapter
            Select-Object
            NetAdapter | Select-Object Name, Status, LinkSpeed
            Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enable True
            Get-NetFirewall -DisplayGroup "Network Discovery"
            Get-WmiObject -query 'select*from SoftwareLicensingService').OA3xOriginalProductKey
            wmic bios get serialnumber
            New-NetFirewallRule -DisplayName "Block Specific IP" -Direction Inbound -Action Block -RemoteAddress "192.168.1.100" -Protocol Any
            New-NetFirewallRule -DisplayName "Block Specific IP Outbound" -Direction Outbound -Action Block -RemoteAddress "192.168.1.100" -Protocol Any 
            Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion
            net users
            net groups
            net user administrator
            Get-LocalGroupMember -Group "Administrators"
            Remove-LocalGroupMember -Group "Administrators" -Member "Domain Users"
        

Get-Module -ListAvailable

GetModule.png GetModules2.png

Get-Module -ListAvailable NetSecurity

NetFirewall1.png

Get-Command -Module WindowsUpdate

GetCommand1.png

Get-Command -Module NetAdapter

GetCommand2.png

Get-Command -Module NetTCPIP

GetCommand3.png

Get-Command -Module TroubleshootingPack

GetCommand4.png

Get-Command -Module NetworkConnectivityStatus

GetCommand5.png

Get-Command -Module NetSecurity

GetCommand6.png

Get-FileHash

GetFileHash1.png

NetAdapter

NetAdapter.png

NetAdapter | Select-Object Name, Status, LinkSpeed

NetAdapter2.png

Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enable True

SetNetFirewall.png

Get-NetFirewallRule -DisplayGroup "Network Discovery"

Get-NetworkFirewall.png

Retrieve computer serial number

serialn.png

New-NetFirewallRule -DisplayName "Block Specific IP" -Direction Inbound -Action Block -RemoteAddress "192.168.1.100" -Protocol Any


FirewallBlock.png

New-NetFirewallRule -DisplayName "Block Specific IP" -Direction Outbound -Action Block -RemoteAddress "192.168.1.100" -Protocol Any

FirewallBlock2.png

Get-ComputerInfo

ComputerInfo1.png

Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion

ComputerInfo2.png ComputerInfo3.png

net user

netuser.png

net group

netgroup.png

net user administrator

netuseradmin.png

Get-LocalGroupMember -Group "Administrators"

GetLocalGroup.png

Add and Remove Local Group Member from Administrators Group

LocalGroup2.png


Working with Files and Directories

Get-ChildItem
New-Item
Get-ChildItem
Remove-Item
echo
mkdir
Move-Item
Copy-Item
ls
    
The Linux commands mkdir, echo, ls, among others can be used in a PowerShell session. NewItem.png GetChildItem.png RemoveItem.png echomkdir.png Item.png


PowerShell Scripting Basics

The following outlines PowerShell Scripting Basics that introduce the core building blocks of automation and system administration with the use of Microsoft's powerful command-line shell and scripting language.

Data Types:



Variables

$Name = "Dave"
$Age = 29
$Services = Get-Service
    

Variables start with $

var.png

Strings

$greeting = "Hello, world"
    $path = 'C:\Users\Dave'
strings.png


Integers


            $a = 10
            $b = 5
        
Integers.png


Arrays


            # Creating an array of strings
            $colors = @("Red", "Green", "Blue")

            # Accessing elements by index
            Write-Output $colors[0] # Output: Red
            Write-Output $colors[1] # Output: Green
            Write-Output $colors[2] # Output: Blue
        
array.png

Adding Items to an Array:


            $colors += "Yellow" # Adds a new item
            Write-Output $colors # Output: Red Green Blue Yellow
        
array2.png

Looping Through an Array:


            foreach ($color in $colors) {
                Write-Output "Color: $color:
            }
        
arrays3.png


Booleans


            $isLoggedIn = $true
            $isAdmin = $false
        
boolean1.png

Using Boolean in if statements:


            if ($isLoggedIn) {
                Write-Output "Access granted."
            } else {
                Write-Output "Access denied."
            }
        
array3.png

Boolean Result from a Comparison:


            $a = 10
            $b = 5

            $isGreater = $a -gt $b  # true
            Write-Output $isGreater # Output: True
        
boolean3.png

Logical Operators:


            $hasPermission = $true
            $isOwner = $false

            if ($hasPermission -and $isOwner) {
                "You can delete this file."
            } elseif ($hasPermissions -or $isOwner) {
                "You can view the file."
            } else {
                "Access denied."
            }
        
boolean4.png

Using -not to Flip a Boolean:


            $isAvailable = $false

            if (-not $isAvailable) {
                "Resource is not available."
            }
        
Boolean5.png


Loops and Conditional Statements

# If-Else
if ($Age -gt 18) {
    Write-Output "Adult"
} else {
    Write-Output "Minor"
}

# ForEach Loop
$services = Get-Service
foreach ($service in $services) {
    Write-Output $service.DisplayName
}
    
loops.png

Objects


            $process = Get-Process notepad
        

The variable $process is now an object with properties such as Name, Id, CPU, etc.

You can access those properties like this:


            $process.Name  # Output: Notepad
            $process.Id    # Output: (the process ID)
        
objects1.png
Checking Object Members with Get-Member:

            $process | Get-Member
        
objects1.png

Creating a Custom Object:


            $user = [PSCustomObject]@{
                FirstName = "Mark"
                LastName = "Thompson"
                Age = 00
            }

            $user.FirstName  # Output: Mark
            $user.Age        # Output: 00
        
objects3.png

Array of Objects:


            $users = @(
                [PSCustomObject]@{ Name = "Alice"; Role = "Admin" },
                [PSCustomObject]@{ Name = "Bob"; Role = "User" }
            )

            foreach ($u in $users) {
                Write-Output "$(Su.Name) is a $($u.Role)"
            }
        
objects4.png

Object Filtering:


            $service = Get-Service
            $running = $services | Where-Object { $_.Status -eq "Running" }
        
objects5.png


Functions

function Greet-User {
    param ($Name)
    Write-Output "Welcome, $Name!"
}

Greet-User -Name "Dave"
    
function.png

simple Function (No Parameters)


            function Say-Hello {
                Write-Output "Hello, world!"
            }

            # Call the function
            Say-Hello
        
function1.png

Function with One Parameter


            function Greet-User {
                param($name)
                Write-Output "Hello, $name!"
            }

            Greet-User -name "Mark"
        
function2.png

Function with Multiple Parameters


            function Add-Numnbers {
                param($a, $b)
                $sum = $a + $b
                Write-Output "The sum is $sum"
            }

            Add-Numbers -a 5 -b 10     # Output: The sum is 15
        
function3.png

Function with Conditional Logic


            function Check-Age {
                param($age)

                if ($age -ge 18) {
                    "You're an adult."
                } else {
                    "You're a minor."
                }
            }

            Check-Age -age 20
        
fucntion4.png

Function that Returns a Value


            function Multiply {
                param($x, $y)
                return $x * $y
            }

            $result = Multiply -x 4 -y 6
            Write-Output "Result: $result"
        
function5.png

Create reusable code blocks


Scripts end with the .ps1 extension.ps1



Permissions and Execution Policy

Get-ExecutionPolicy
Set-ExecutionPolicy RemoteSigned
    
ExecutePolicy.png

Policies:

Might need admin privileges




Useful Tools and Debugging

Write-Host:

Write-Host is used to display output directly output directly to the console.


            function Test-ConnectionStatus {
                param($server)

                Write-Host "Starting connection check..." -ForegroundColor Cyan

                if (Test-Connection -ComputerName $server -Count 1 -Quiet) {
                    Write-Host "$server is online." -ForegroundColor Green
                } else {
                    Write-Host "$server is offline or unreachable." -ForegroundColor Red
                }

                Write-Host "Finished connection check." -ForegroundColor Cyan
            }

            Test-ConnectionStatus -server "example.com"
        
WriteHost.png

Write-Output:

Write-Output sends data to the output stream, which makes it available for further use such as capturing into a variable, piping to another command, and redirecting a file.

try {
    Get-Item "C:\fakefile.txt"
} catch {
    Write-Output "File not found!"
}
    
file.png

Start-Transcript:

Start-Transcript is a built-in command that starts recording everything that happens in the PowerShell session, including the commands run, their output, errors, and messages to a log file.


            # Start logging the session
            Start-Transcript -Path "C:\Logs\debug-log.txt" -Append

            Write-Host "Starting server check..."

            $server = "example.com"

            Write-Host "Pinging $server..."
            if (Test-Connection -ComputerName $server -Count 1 -Quiet) {
                Write-Host "$server is online."
            } else {
                Write-Host "$server is offline or unreachable."
            }

            Write-Host "Script complete."

            # Stop logging
            Stop-Transcript
        
StartTranscript.png

Try/Catch - Basic Try/Catch Block:


        try {
            # This will fail if the file doesn't exist
            Get-Content "C:\missing-file.txt"
        }
        catch {
            Write-Host "An error occurred: $_"
        }
    
try1.png

Try/Catch with a Specific Error Action


            try {
                # Force PowerShell to treat the error as terminating
                Remove-Item "C:\nonexistent.txt" -ErrorAction Stop
            }
            catch {
                Write-Host "Failed to delete file: $_"
            }
        
try2.png

Finally:

Using Finaly to Always Run Cleanup


        try {
            Write-Host "Trying risky operation..."
            Get-Content "C:\nonexistent.txt" -ErrorAction stop
        }
        catch {
            Write-Host "Caught an error: $_"
        }
        finally {
            Write-Host "Cleaning up... This always runs."
        }
    
finallty.png



Real-World Use Cases


Batch user creation in AD

1. The first step is to create a CSV, for this example, I'm using Notepad++ to create a .csv file with the following attributes.

csv0.png

2. Then I'm going to use this script to import the csv file to create two new user accounts in Active Directory.

ScriptCode0.png

3. Two new user accounts in Active Directory Users and Computers in the TestUsers OU.

csv00.PNG

Automating updates

WindowsUpdate.png WindowsUpdate2.png WindowsUpdate3.png

Backing up and archiving logs

Backup.png

Scheduled tasks and reporting

tasksched1.png tasksched2.png tasksched3.png tasksched4.png tasksched5.png tasksched6.png tasksched7.png tasksched8.png tasksched9.png tasksched10.png

PowerShell gives IT professionals control and automation in ways that save time, reduce errors, and increase system reliability. Mastering its fundamentals is the first step to becoming a true IT automation pro.

Back to Home