PowerShell is Microsoft’s command-line shell and scripting language for automating IT work. Unlike traditional shells, it passes objects instead of text between commands, so you can filter, sort, and export information about computers, users, and services with short, readable commands.

If you manage Windows computers, servers, or Microsoft 365, you’ll run into PowerShell sooner or later. Many admin tasks have no button in a graphical tool, and the ones that do are slow when you need to repeat them for fifty users or a hundred computers. A few lines of PowerShell can do the same job in seconds, the same way every time.

This guide is for IT administrators who are new to PowerShell. You’ll learn how commands are named, how the pipeline works, the basics of variables and scripts, and a set of everyday admin tasks you can adapt right away.

Windows PowerShell vs. PowerShell 7

There are two versions you’ll see:

Windows PowerShell 5.1PowerShell 7
Comes withEvery current version of WindowsA separate install
Command to start itpowershellpwsh
Runs onWindows onlyWindows, macOS, and Linux
UpdatesSecurity fixes onlyNew releases and features

Both can be installed side by side. Use PowerShell 7 for new work. The current long-term support (LTS) release is PowerShell 7.6, released in March 2026 and supported by Microsoft until November 2028. Keep Windows PowerShell 5.1 for the occasional older module that hasn’t been updated.

To install PowerShell 7 on Windows, open a terminal and run:

winget install --id Microsoft.PowerShell --source winget

On a Mac, brew install --cask powershell works, and Microsoft publishes packages for the major Linux distributions. Then open Windows Terminal (or any terminal) and type pwsh. For editing scripts, Visual Studio Code with Microsoft’s PowerShell extension gives you highlighting, autocomplete, and a debugger.

Cmdlets: Verb-Noun Commands

PowerShell commands are called cmdlets (pronounced “command-lets”), and they follow a Verb-Noun pattern that makes them easy to guess:

CmdletWhat it does
Get-ProcessLists running processes
Get-ServiceLists services and their status
Stop-ServiceStops a service
Get-ChildItemLists files and folders
Copy-ItemCopies files or folders
Test-ConnectionPings a computer

The verbs come from an approved list, so once you know Get, Set, New, Remove, Start, Stop, and Test, you can guess hundreds of commands. Parameters start with a dash, like -Name or -Path, and you can press Tab to complete cmdlet and parameter names.

Three Commands That Teach You the Rest

Get-Command -Noun *Service*        # find commands by name
Get-Help Get-ChildItem -Examples   # see examples for a command
Get-Process | Get-Member           # see what properties an object has
  • Get-Command finds commands. -Noun *Service* lists everything that works with services.
  • Get-Help shows documentation. Add -Examples for ready-to-use examples, or -Online to open the web page. Run Update-Help once, as administrator, to download the full help files.
  • Get-Member shows the properties and methods of whatever a command returns. It’s the key to working with objects, as you’ll see next.

Familiar commands still work through aliases: cd, dir, cls, and copy all map to PowerShell cmdlets on Windows. They’re fine at the prompt, but write the full cmdlet names in scripts so they’re easy to read and work the same everywhere. If you already know Bash, the Linux terminal guide shows the equivalent commands on the other side.

The Big Idea: Objects and the Pipeline

In most shells, commands pass text to each other, and you cut that text apart to find what you need. PowerShell passes objects, structured data with named properties. That’s what makes it powerful.

The pipe character | sends the output of one command into the next:

Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 Name, Id, CPU

This gets every running process, sorts them by the CPU property, highest first, and keeps the top five with three columns. There’s no text parsing: CPU is a real property of each process object.

The four pipeline cmdlets you’ll use constantly are:

CmdletWhat it doesExample
Where-ObjectKeeps only matching objectsWhere-Object Status -eq 'Running'
Sort-ObjectSorts by a propertySort-Object Length -Descending
Select-ObjectPicks properties or the first/last itemsSelect-Object -First 10 Name
ForEach-ObjectRuns code for each objectForEach-Object { $_.Name.ToUpper() }

Inside a script block, $_ means “the current object in the pipeline.”

Here’s a practical example: find the largest files in a folder, with their size in megabytes:

Get-ChildItem -Path $PSHOME -File -Recurse |
    Where-Object Length -gt 1MB |
    Sort-Object Length -Descending |
    Select-Object -First 3 Name, @{ Name = "SizeMB"; Expression = { [math]::Round($_.Length / 1MB, 1) } }
Name                              SizeMB
----                              ------
System.Management.Automation.dll    6.90
Microsoft.CodeAnalysis.CSharp.dll   6.50
Microsoft.CodeAnalysis.dll          2.90

$PSHOME is PowerShell’s own install folder, so this works on any computer; swap in a path like C:\Users to hunt for space hogs. PowerShell understands size units like 1MB and 1GB, and the @{ Name = ...; Expression = ... } part is a calculated property that adds a new column.

Because the results are objects, you can send them anywhere with one more command: | Export-Csv report.csv for Excel, | ConvertTo-Json for an API, or | Out-GridView for a sortable window on Windows. Working With JSON and CSV Data in PowerShell covers both formats in depth.

Variables, Arrays, and Hashtables

Variables start with $. PowerShell figures out the type for you:

$server = "web01"
$ports = 80, 443
$employee = @{ Name = "Ana Torres"; Department = "IT"; Laptop = "LT-1042" }

"Checking $server on ports $($ports -join ', ')"
"$($employee.Name) works in $($employee.Department)"
Checking web01 on ports 80, 443
Ana Torres works in IT
  • A comma-separated list creates an array.
  • @{ ... } creates a hashtable, a set of key-value pairs, like a Python dictionary.
  • Inside double quotes, variables are expanded. For anything more than a plain variable, like a property, wrap it in $( ... ). Single quotes never expand variables.

Comparison Operators

PowerShell uses words instead of symbols for comparisons, because > and < are used for redirection:

OperatorMeaningExample (all True)
-eq, -neEqual, not equal"web01" -eq "WEB01"
-gt, -lt, -ge, -leGreater/less than (or equal)5 -gt 3
-likeWildcard match"web01" -like "web*"
-matchRegular expression match"PC-ACCT-07" -match "ACCT"
-containsA list contains a value$ports -contains 443

Comparisons are case-insensitive by default; add a c for case-sensitive versions, like -ceq.

Making Decisions and Repeating Work

$freePercent = 12

if ($freePercent -lt 10) {
    "Critical: only $freePercent% free"
}
elseif ($freePercent -lt 20) {
    "Warning: $freePercent% free"
}
else {
    "OK"
}
Warning: 12% free

To repeat work, use foreach with a collection:

$servers = "web01", "web02", "db01"
foreach ($s in $servers) {
    "Backing up $s"
}
Backing up web01
Backing up web02
Backing up db01

Handling Errors

Wrap anything that might fail in try/catch. Add -ErrorAction Stop so the error is caught:

try {
    Get-Content -Path ./missing-file.txt -ErrorAction Stop
}
catch {
    Write-Warning "Could not read the file: $($_.Exception.Message)"
}
WARNING: Could not read the file: Cannot find path 'C:\Scripts\missing-file.txt' because it does not exist.

Many cmdlet errors are “non-terminating,” meaning PowerShell prints them and keeps going. -ErrorAction Stop turns them into errors that catch can handle.

Everyday Admin Tasks

The examples in this section are for Windows. Most work in both Windows PowerShell 5.1 and PowerShell 7, and some need an administrator window (right-click PowerShell and choose Run as administrator).

Check Services

Get-Service | Where-Object Status -eq 'Stopped'
Get-Service -Name Spooler
Restart-Service -Name Spooler

The first line lists stopped services; the others check and restart the Print Spooler, a classic fix for stuck print jobs.

Read Event Logs

# The 20 newest errors in the System log
Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 2 } -MaxEvents 20

# Failed sign-ins in the last 24 hours (needs administrator)
Get-WinEvent -FilterHashtable @{
    LogName   = 'Security'
    Id        = 4625
    StartTime = (Get-Date).AddDays(-1)
}

-FilterHashtable filters inside the event log instead of loading everything first, which is much faster. Event ID 4625 is a failed logon; a burst of them can mean someone is guessing passwords, a good reason for two-factor authentication.

Check Disk Space

Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3" |
    Select-Object DeviceID,
        @{ Name = "SizeGB"; Expression = { [math]::Round($_.Size / 1GB, 1) } },
        @{ Name = "FreeGB"; Expression = { [math]::Round($_.FreeSpace / 1GB, 1) } }

Get-CimInstance reads system information through CIM, Windows’ management interface. DriveType=3 means local hard drives. Add -ComputerName PC01 to ask another computer.

Test Network Connections

Test-Connection -TargetName server01 -Count 2          # ping (PowerShell 7)
Test-NetConnection -ComputerName server01 -Port 443    # is a TCP port open? (Windows)
Test-Connection -TargetName server01 -TcpPort 443      # the same in PowerShell 7, on any OS

In Windows PowerShell 5.1, Test-Connection uses -ComputerName instead of -TargetName. Checking a port is often more useful than a ping, since many servers block ping. If you’re not sure which port a service uses, see the well-known port numbers.

Manage Local Users

Get-LocalUser | Where-Object Enabled | Select-Object Name, LastLogon

$password = Read-Host -AsSecureString "Password for the new account"
New-LocalUser -Name "mlopez" -FullName "Maria Lopez" -Password $password
Add-LocalGroupMember -Group "Users" -Member "mlopez"

Read-Host -AsSecureString asks for the password without showing it or saving it in your script. For domain accounts, the Active Directory module (part of RSAT) adds cmdlets like Get-ADUser, New-ADUser, and Search-ADAccount. For example, Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 -UsersOnly lists accounts nobody has used in 90 days.

Run Commands on Remote Computers

Invoke-Command -ComputerName PC01, PC02, PC03 -ScriptBlock {
    Get-Service -Name Spooler
}

PowerShell Remoting runs the script block on each computer at the same time and sends the results back, with a PSComputerName property saying where each came from. Remoting is on by default on Windows Server; on client computers, run Enable-PSRemoting (as administrator) first. For an interactive session on one machine, use Enter-PSSession -ComputerName PC01, and Exit-PSSession to leave.

Practice Safely: -WhatIf and -Confirm

Cmdlets that change things usually support -WhatIf, which shows what would happen without doing it:

Remove-Item -Path C:\Temp\*.log -WhatIf
What if: Performing the operation "Remove File" on target "C:\Temp\app.log".

Use -WhatIf every time you run a command that deletes, disables, or changes something for the first time, especially with wildcards or a pipeline that might match more than you expect. -Confirm asks before each change.

Writing Your First Script

A script is just a text file of commands saved with a .ps1 extension. Here’s a complete one that builds a disk space report, marks drives that are low on space, and saves the results as a CSV file you can open in Excel. Save it as Get-DiskReport.ps1:

param(
    [int]$WarningPercent = 20,
    [string]$ReportPath = "./disk-report.csv"
)

$report = Get-PSDrive -PSProvider FileSystem |
    Where-Object { $null -ne $_.Used -and ($_.Used + $_.Free) -gt 0 } |
    ForEach-Object {
        $total = $_.Used + $_.Free
        $freePercent = [math]::Round($_.Free / $total * 100, 1)
        [PSCustomObject]@{
            Drive       = $_.Name
            SizeGB      = [math]::Round($total / 1GB, 1)
            FreeGB      = [math]::Round($_.Free / 1GB, 1)
            FreePercent = $freePercent
            Status      = if ($freePercent -lt $WarningPercent) { "LOW" } else { "OK" }
        }
    }

$report | Format-Table -AutoSize
$report | Export-Csv -Path $ReportPath -NoTypeInformation
Write-Output "Report saved to $ReportPath"

A few new ideas:

  • param( ... ) defines the script’s parameters, with defaults. Run it as .\Get-DiskReport.ps1 or change the values: .\Get-DiskReport.ps1 -WarningPercent 15 -ReportPath C:\Reports\disks.csv.
  • [PSCustomObject]@{ ... } builds your own object with exactly the columns you want, so Format-Table and Export-Csv work on it like any built-in object.
  • Get-PSDrive -PSProvider FileSystem lists drives on any operating system; on Windows, the Get-CimInstance version above gives the same information for remote computers too.

The output looks like this:

Drive SizeGB FreeGB FreePercent Status
----- ------ ------ ----------- ------
C     476.00  61.20       12.90 LOW
D     931.50 402.70       43.20 OK

Report saved to ./disk-report.csv

Execution Policy

The first time you run a script on Windows, you may see an error saying running scripts is disabled. That’s the execution policy, a safety setting that blocks scripts by default on Windows clients. Allow your own scripts, and signed scripts from the internet, with:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

RemoteSigned runs local scripts but requires downloaded scripts to be signed. The execution policy isn’t a security boundary, but it prevents running a downloaded script by accident. Don’t set it to Unrestricted or Bypass just to make an error go away.

Run It on a Schedule

To run the report every morning, register it with Task Scheduler:

$action  = New-ScheduledTaskAction -Execute "pwsh.exe" -Argument "-NoProfile -File C:\Scripts\Get-DiskReport.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 7am
Register-ScheduledTask -TaskName "Daily Disk Report" -Action $action -Trigger $trigger

Keep your scripts in Git so you have a history of every change, and include them in your backups.

Real-World Example: Usernames From a CSV

A common request: HR sends a spreadsheet of new hires, and you need accounts for all of them. Save the list as new-hires.csv:

FirstName,LastName,Department
Maria,Lopez,Finance
James,Carter,IT
Sofia,Nguyen,Sales

Then build the usernames (first initial plus last name, in lowercase) and check them before creating anything:

Import-Csv ./new-hires.csv | ForEach-Object {
    $username = ($_.FirstName.Substring(0, 1) + $_.LastName).ToLower()
    [PSCustomObject]@{
        Name       = "$($_.FirstName) $($_.LastName)"
        Username   = $username
        Department = $_.Department
    }
} | Format-Table
Name         Username Department
----         -------- ----------
Maria Lopez  mlopez   Finance
James Carter jcarter  IT
Sofia Nguyen snguyen  Sales

Import-Csv turns each row into an object, with the column headers as property names. Once the list looks right, replace the [PSCustomObject] part with New-LocalUser or New-ADUser (run with -WhatIf first), and fifty accounts take as long as one.

Common Beginner Mistakes

  • Running everything as administrator. Open an elevated window only for tasks that need it. A mistake in an admin window can do far more damage.
  • Skipping -WhatIf. One wrong wildcard can delete or disable much more than you meant to.
  • Treating output as text. Use Where-Object and Select-Object on properties instead of searching the screen output. Use Get-Member to see what’s available.
  • Formatting too early. Format-Table and Format-List are for the screen. Put them at the very end of a pipeline, never before Export-Csv or another command.
  • Storing passwords in scripts. Use Read-Host -AsSecureString, Get-Credential, or Microsoft’s SecretManagement module, never plain text in a .ps1 file.
  • Running scripts from the internet without reading them. Read every line first, and test in a lab or on one computer before running it across your network.
  • Using aliases in scripts. gci | ? { $_.Length -gt 1MB } works, but Get-ChildItem | Where-Object Length -gt 1MB is what the next admin will understand.

Quick Reference

TaskCommand
Find a commandGet-Command -Noun *Service*
Get help with examplesGet-Help Get-Service -Examples
See an object’s propertiesGet-Process | Get-Member
List filesGet-ChildItem -Path C:\Logs -Recurse
Read a fileGet-Content -Path .\log.txt -Tail 20
Filter resultsWhere-Object Status -eq 'Running'
Sort and pickSort-Object CPU -Descending | Select-Object -First 5
Export to CSVExport-Csv -Path .\report.csv -NoTypeInformation
Import a CSVImport-Csv -Path .\users.csv
Ping or test a portTest-Connection server01 / Test-NetConnection server01 -Port 443
Run on remote computersInvoke-Command -ComputerName PC01 -ScriptBlock { ... }
Preview a changeAdd -WhatIf

Frequently Asked Questions

Is PowerShell hard to learn?

Not if you already use a command line. The Verb-Noun naming, Tab completion, and Get-Help make it easy to explore. Start by using it for small, read-only tasks like checking services or disk space, then automate one repetitive task at a time.

Should I learn PowerShell or Python?

For Windows, Active Directory, and Microsoft 365 administration, learn PowerShell first: it’s built for those systems and their management modules are written for it. Python is broader and better for data work and general programming; see Python Basics. Many IT professionals end up using both.

What’s the difference between PowerShell and Command Prompt?

Command Prompt (cmd.exe) is the old Windows shell, with a small set of text-based commands and batch files. PowerShell is a full scripting language with objects, thousands of cmdlets, remoting, and modules. Use PowerShell for anything new. For a side-by-side comparison, see PowerShell vs. Command Prompt: Understanding the Differences.

Does PowerShell work on Linux and macOS?

PowerShell 7 does. Core commands, scripting, and many modules work everywhere, but Windows-specific cmdlets, like those for services, event logs, local users, and the registry, only work on Windows.

Is PowerShell safe?

PowerShell is a powerful tool, which is why attackers like it too. Use the execution policy, run with the least privilege you need, keep PowerShell updated, and turn on logging (script block logging and transcripts) so you can see what ran. The cybersecurity fundamentals guide covers the broader principles.

Conclusion

PowerShell turns repetitive IT work into short, repeatable commands. Learn the Verb-Noun naming and the three discovery commands (Get-Command, Get-Help, and Get-Member), think in objects and pipelines, and use -WhatIf before you change anything. Start with read-only tasks like checking services, disk space, and event logs, then turn the commands you run most often into scripts. Every task you automate is time you get back, and it’s done the same way every time.