PowerShell is the command-line shell and scripting language that Microsoft built for administrators. If you manage Windows servers, Microsoft 365, Azure, SQL Server or even Linux machines, it is the tool that turns hours of clicking into a few lines you can run again and again. This guide explains it from the ground up: how a command is built, why PowerShell is different from older shells, and then the commands you will use every day, each one with an explanation of why it works the way it does.
You do not need any programming background. Read the first four sections slowly, because they explain the ideas that make everything else easy. After that, use the guide as a reference and jump to the topic you need.
Contents
- 1. What PowerShell is, and how to open it
- 2. Cmdlets, help and discovery
- 3. Objects and the pipeline
- 4. Variables, types and operators
- 5. Making decisions and repeating work
- 6. Files, folders and text
- 7. CSV, JSON and XML
- 8. Processes, services, event logs and system information
- 9. Users, groups and Active Directory
- 10. Networking and the web
- 11. Disks, the registry and scheduled tasks
- 12. Remoting: run commands on other computers
- 13. Writing scripts and functions
- 14. Errors, -WhatIf and safe automation
- 15. Modules and the PowerShell Gallery
- 16. Credentials, execution policy and security
- 17. Ready-made recipes
- 18. PowerShell for people who know Bash
- 19. Good habits and common mistakes
1. What PowerShell is, and how to open it
Older shells such as cmd.exe or Bash pass text from one command to the next, and you have to cut that text apart with tools like grep and awk. PowerShell passes objects. An object is a thing with named properties: a process has a Name, an Id and a CPU value; a file has a Length and a LastWriteTime. Because of this, you ask for “the processes using more than 500 MB” instead of searching for numbers inside text. This one idea is the reason PowerShell is so powerful.
Two versions, and why it matters
| Name | Program | Where | Notes |
|---|---|---|---|
| Windows PowerShell 5.1 | powershell.exe |
Built into Windows 10, 11 and Server | Windows only. No longer receives new features, but is on every Windows machine and still needed for some older modules. |
| PowerShell 7.x | pwsh.exe |
Install it yourself (free) | Cross-platform (Windows, Linux, macOS), faster, with newer features. This is the version to learn. |
Most commands in this guide work in both. Where something differs, a note says so. Install version 7 with winget install Microsoft.PowerShell, then start it by typing pwsh.
Opening it and first checks
On Windows, right-click the Start button and choose Terminal (or Windows PowerShell). To run commands that change the system you need an elevated window: right-click and choose Run as administrator. The prompt does not say it, so check:
$PSVersionTable # shows the PowerShell version and edition
$PSVersionTable.PSVersion # just the version number
# Am I running as administrator?
([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
whoami # the account you are using
$env:COMPUTERNAME # the computer name
Keyboard tricks that save a lot of typing: Tab completes commands, parameters and paths (press it repeatedly to cycle); Up arrow recalls earlier commands; Ctrl+R searches your history as you type; Ctrl+C stops a running command; Clear-Host (or cls) clears the screen.
2. Cmdlets, help and discovery
PowerShell commands are called cmdlets (pronounced “command-lets”). They always follow the pattern Verb-Noun: Get-Process, Stop-Service, New-Item, Remove-Item. The verb says what you do, the noun says what you do it to. Because the names are predictable, you can often guess a command you have never used.
| Verb | Meaning | Example |
|---|---|---|
Get |
Read or list. Safe: it changes nothing | Get-Service |
Set |
Change an existing thing | Set-Service |
New |
Create | New-Item |
Remove |
Delete | Remove-Item |
Start, Stop, Restart |
Control something that runs | Restart-Service |
Enable, Disable |
Turn on or off | Disable-NetAdapter |
Import, Export |
Bring data in or send it out | Export-Csv |
Invoke |
Run an action | Invoke-Command |
Parameters start with a dash and change what the cmdlet does: Get-Process -Name chrome. Many accept shortened names, as long as they are unambiguous (-Comp for -ComputerName), and Tab completes them. A switch is a parameter without a value: Get-ChildItem -Recurse.
The three commands that teach you everything else
Get-Command *service* # find commands by part of a name
Get-Command -Verb Get -Noun *Net* # all "Get" commands about networking
Get-Help Get-Service -Examples # short explanations with working examples (start here)
Get-Help Get-Service -Full # everything: every parameter, with notes
Get-Help about_Operators # background articles on concepts
Update-Help # download the latest help (run once as administrator)
Get-Help with -Examples is the best habit you can build. Instead of searching the web, read the examples that ship with the command. The third discovery command is Get-Member, explained in the next section.
Aliases
Aliases are short names for cmdlets: ls and dir run Get-ChildItem, cd runs Set-Location, cat runs Get-Content, ? runs Where-Object, % runs ForEach-Object. They are fine for typing at the console. In a script, use the full names so that the next person can read it. Check what an alias means with Get-Alias ls.
3. Objects and the pipeline
The pipe symbol | sends the objects that one command produces into the next command. Try it:
Get-Process # a table of processes
Get-Process | Get-Member # what is inside one process object?
Get-Member lists the properties (data, such as Name, Id, WorkingSet) and the methods (actions, such as Kill()) of the objects. PowerShell shows you only a few columns by default; the object actually carries many more. To see everything about one item:
Get-Process -Name explorer | Select-Object * # every property of that process
Get-Process -Name explorer | Format-List * # the same, as a list
The five cmdlets you will use in almost every line
| Cmdlet | Job | Example |
|---|---|---|
Where-Object |
Keep only the objects that match a condition | Get-Service | Where-Object Status -eq 'Running' |
Select-Object |
Choose which properties (columns) or how many items | Get-Process | Select-Object Name, Id -First 5 |
Sort-Object |
Sort by a property | Get-Process | Sort-Object WorkingSet -Descending |
ForEach-Object |
Do something for each object | 1..3 | ForEach-Object { $_ * 2 } |
Group-Object, Measure-Object |
Group and count, or add up | Get-Service | Group-Object Status |
Filtering: two ways to write it
# Simple form: one property, one comparison
Get-Service | Where-Object Status -eq 'Running'
# Script block form: any condition. $_ means "the current object"
Get-Process | Where-Object { $_.WorkingSet -gt 500MB -and $_.Name -ne 'Idle' }
PowerShell understands the size suffixes KB, MB, GB and TB, so 500MB is 524,288,000 bytes. Notice that comparisons use words (-eq, -gt, -like) instead of symbols, because the symbols > and < are used for redirection.
Selecting, sorting and calculating
# The 5 processes using the most memory, with a readable column
Get-Process |
Sort-Object WorkingSet -Descending |
Select-Object -First 5 Name, Id, @{ Name = 'MemoryMB'; Expression = { [math]::Round($_.WorkingSet / 1MB) } }
The piece starting with @{ Name = ...; Expression = ... } is a calculated property: you invent a new column and say how to compute it for each object. A line ending with a pipe can continue on the next line, which keeps long commands readable.
Get-Service | Group-Object Status # how many services are running vs stopped
Get-ChildItem C:\Windows -File | Measure-Object Length -Sum -Average -Maximum
Get-Process | Select-Object -ExpandProperty Name # a plain list of values, not objects
(Get-Process).Count # how many items?
Get-Process chrome | Measure-Object WorkingSet -Sum # total memory used by all Chrome processes
-ExpandProperty is important: Select-Object Name returns objects that have a Name, while -ExpandProperty Name returns the plain names themselves.
Formatting is the last step
Get-Service | Format-Table Name, Status -AutoSize # table
Get-Service W32Time | Format-List * # list of all properties
Get-Process | Out-GridView # a searchable, sortable window (Windows only)
Rule: put Format-Table and Format-List at the very end of a pipeline. They turn objects into display text, so nothing useful can follow them. If you want to export or filter further, do it before formatting.
Comparing two lists
Compare-Object -ReferenceObject (Get-Content old.txt) -DifferenceObject (Get-Content new.txt)
# => marks lines only in the new file, <= lines only in the old file
4. Variables, types and operators
A variable starts with $. You do not declare it first.
$name = 'Alice'
$count = 42
$today = Get-Date
$services = Get-Service # a variable can hold many objects
"Hello, $name" # double quotes expand variables
'Hello, $name' # single quotes do NOT expand: prints the text as it is
"Today is $($today.DayOfWeek)" # $( ) runs an expression inside a string
"Free: $([math]::Round(12345678 / 1MB, 1)) MB"
Types
$age = [int]'42' # force a type with a cast
[datetime]'2026-12-31' # text to a date
$n = 5; $n.GetType().Name # Int32
$x = [string]123 ; $x.Length # 3
[math]::Round(3.14159, 2) # 3.14; [math]:: calls .NET static methods
[guid]::NewGuid()
Arrays and hashtables
$list = 'a', 'b', 'c' # an array
$list[0] # first item; $list[-1] is the last
$list.Count
1..5 # a range: 1,2,3,4,5
$server = @{ Name = 'web01'; Port = 443; Online = $true } # a hashtable: key-value pairs
$server.Name
$server['Port']
$server.Role = 'Frontend' # add a key
$obj = [PSCustomObject]@{ Name = 'web01'; Port = 443 } # your own object (best for reports)
A warning about arrays: $list += 'd' looks like it adds an item, but PowerShell creates a whole new array each time, which becomes very slow with thousands of items. For big loops use a list: $items = [System.Collections.Generic.List[string]]::new(); $items.Add('x').
Operators
| Operator | Meaning | Example |
|---|---|---|
-eq, -ne |
Equal, not equal | $a -eq 5 |
-gt, -ge, -lt, -le |
Greater, greater or equal, less, less or equal | $a -gt 10 |
-like, -notlike |
Wildcard match (* and ?) |
'server01' -like 'server*' |
-match, -notmatch |
Regular expression match | 'ab12' -match '\d+' |
-contains, -in |
Is an item in a collection? | $list -contains 'a' or 'a' -in $list |
-and, -or, -not (or !) |
Combine conditions | ($a -gt 1) -and ($b -lt 5) |
-replace, -split, -join |
Replace (regex), split, join text | 'a,b,c' -split ',' |
Comparisons ignore upper and lower case by default ('A' -eq 'a' is true). Add a c to be strict: -ceq. When you test for nothing, write $null on the left: $null -eq $value, which behaves correctly even if $value is an array.
Useful built-in variables
| Variable | Contains |
|---|---|
$_ or $PSItem |
The current object inside Where-Object or ForEach-Object |
$? |
True if the last command succeeded |
$LASTEXITCODE |
Exit code of the last external program (ping, git…) |
$Error |
List of recent errors; $Error[0] is the latest |
$env:USERNAME, $env:TEMP, $env:PATH |
Environment variables |
$PSScriptRoot |
The folder of the running script |
$HOME, $PWD |
Home folder, current folder |
Longer text: here-strings
$body = @"
Hello $name,
the report for $($today.ToString('yyyy-MM-dd')) is ready.
"@
A here-string starts with @" alone on its line and ends with "@ at the very start of a line. With @' and '@ it does not expand variables.
5. Making decisions and repeating work
if ($free -lt 10) {
'Disk is almost full'
} elseif ($free -lt 20) {
'Disk is getting full'
} else {
'Disk is fine'
}
switch ($status) {
'Running' { 'All good' }
'Stopped' { 'Needs attention' }
default { 'Unknown' }
}
The same kinds of loops exist, and each suits a different job:
foreach ($svc in Get-Service) { # when you already have the items in memory
if ($svc.Status -eq 'Stopped') { $svc.Name }
}
Get-Service | ForEach-Object { $_.Name } # when you stream items down the pipeline
for ($i = 1; $i -le 5; $i++) { "Round $i" } # a counter
$tries = 0
while ($tries -lt 3 -and -not (Test-Path C:\done.flag)) {
Start-Sleep -Seconds 10 # wait, then check again
$tries++
}
# Skip or stop inside a loop: continue (next item) break (leave the loop)
PowerShell 7 adds a few handy shortcuts:
$mode = $debug ? 'verbose' : 'quiet' # ternary operator
$name = $userName ?? 'guest' # use "guest" if $userName is $null
Test-Path C:\a.txt && Get-Content C:\a.txt # run the second only if the first succeeded
Get-Item C:\missing.txt -ErrorAction SilentlyContinue || 'file not found' # run the second only if the first failed
6. Files, folders and text
PowerShell treats many things as “drives” that you navigate the same way: C: for files, HKLM: and HKCU: for the registry, Cert: for certificates, Env: for environment variables. List them with Get-PSDrive.
| Task | Command |
|---|---|
| Where am I? Go somewhere | Get-Location, Set-Location C:\Logs (aliases pwd, cd) |
| List | Get-ChildItem (dir, ls), with -Recurse, -File, -Directory, -Hidden |
| Create folder or file | New-Item -ItemType Directory -Path C:\Logs\2026, New-Item -ItemType File -Path a.txt |
| Copy, move, rename | Copy-Item a.txt b.txt, Move-Item a.txt D:\, Rename-Item a.txt c.txt |
| Delete | Remove-Item a.txt, Remove-Item C:\Temp\old -Recurse -Force |
| Does it exist? | Test-Path C:\a.txt |
| Build or split a path | Join-Path C:\Logs app.log, Split-Path C:\Logs\app.log -Leaf |
| Compress, extract | Compress-Archive -Path C:\Logs\* -DestinationPath logs.zip, Expand-Archive logs.zip -DestinationPath C:\Restore |
| Hash of a file | Get-FileHash setup.exe -Algorithm SHA256 |
Finding files
# Files changed in the last 7 days
Get-ChildItem C:\Data -Recurse -File | Where-Object LastWriteTime -gt (Get-Date).AddDays(-7)
# The 10 biggest files on a drive, in MB
Get-ChildItem C:\ -Recurse -File -ErrorAction SilentlyContinue |
Sort-Object Length -Descending | Select-Object -First 10 FullName,
@{ Name = 'MB'; Expression = { [math]::Round($_.Length / 1MB, 1) } }
# Fast filtering by name: -Filter is done by the file system, -Include is done afterwards
Get-ChildItem C:\Logs -Filter *.log -Recurse
-ErrorAction SilentlyContinue hides “access denied” messages for folders you cannot read. It is fine for a search, but never use it to hide errors in a command that changes things.
Reading and writing text
Get-Content C:\Logs\app.log # the whole file, as one string per line
Get-Content C:\Logs\app.log -Tail 20 # the last 20 lines
Get-Content C:\Logs\app.log -Tail 20 -Wait # follow the file live, like "tail -f" (Ctrl+C to stop)
Get-Content big.txt -TotalCount 5 # the first 5 lines
Set-Content notes.txt 'first line' # create or overwrite
Add-Content notes.txt 'another line' # append
Get-Process | Out-File procs.txt # save what you would see on screen
'text' | Out-File a.txt -Append -Encoding utf8
Select-String -Path C:\Logs\*.log -Pattern 'error|failed' # search, like grep
Select-String -Path C:\Logs\*.log -Pattern 'timeout' -Context 2,2 # 2 lines before and after
Encoding differs between versions. In Windows PowerShell 5.1, Out-File and > write UTF-16 by default and Set-Content -Encoding UTF8 adds a byte-order mark. PowerShell 7 writes UTF-8 without the mark. When another program must read your file, set -Encoding explicitly.
Replace text in files, safely
(Get-Content app.config) -replace 'Server=old01', 'Server=new01' | Set-Content app.config
The brackets matter: they read the whole file first, then write. Without them you read and write the same file at once, which can empty it. Always keep a copy first: Copy-Item app.config app.config.bak.
7. CSV, JSON and XML
Because PowerShell works with objects, turning data into files and back is one command each way.
# CSV: objects to file, and back
Get-Service | Select-Object Name, Status, StartType | Export-Csv services.csv -NoTypeInformation
$rows = Import-Csv services.csv # each row is an object, columns are properties
$rows | Where-Object Status -eq 'Stopped'
# JSON: great for APIs and configuration
$cfg = Get-Content config.json -Raw | ConvertFrom-Json
$cfg.database.host
$cfg.database.host = 'db02'
$cfg | ConvertTo-Json -Depth 5 | Set-Content config.json
# XML
[xml]$xml = Get-Content settings.xml
$xml.configuration.appSettings.add | Select-Object key, value
Two details that trip people up: -NoTypeInformation is needed in Windows PowerShell 5.1 (otherwise a useless first line is added; PowerShell 7 leaves it out), and ConvertTo-Json stops at two levels of nesting unless you raise -Depth, silently turning deeper objects into text.
For Excel files, install the free ImportExcel module (section 15). For data you want to save and reload as live objects, Export-Clixml and Import-Clixml keep the types.
8. Processes, services, event logs and system information
Processes
Get-Process # all processes
Get-Process -Name chrome # by name (no .exe)
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5
Stop-Process -Name notepad # end by name
Stop-Process -Id 4321 -Force # end by ID, force
Start-Process notepad.exe # start a program
Start-Process powershell -Verb RunAs # start it elevated (asks for approval)
Wait-Process -Name setup # pause the script until it ends
Services
Get-Service # all services
Get-Service -Name W32Time, Spooler
Get-Service | Where-Object { $_.Status -eq 'Stopped' -and $_.StartType -eq 'Automatic' } # should be running!
Start-Service Spooler
Stop-Service Spooler
Restart-Service Spooler -Force
Set-Service -Name Spooler -StartupType Disabled # Automatic | Manual | Disabled
Get-Service -ComputerName srv01 -Name W32Time # a remote computer (Windows PowerShell 5.1)
The second query is one of the most useful checks after a reboot: services set to start automatically that are not running.
Event logs: find out what went wrong
# Errors in the System log during the last 24 hours
Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 2; StartTime = (Get-Date).AddHours(-24) }
# Failed sign-ins (needs an administrator window)
Get-WinEvent -FilterHashtable @{ LogName = 'Security'; Id = 4625; StartTime = (Get-Date).AddDays(-1) } |
Select-Object TimeCreated, @{ n = 'Account'; e = { $_.Properties[5].Value } }, @{ n = 'From'; e = { $_.Properties[19].Value } }
# What logs exist?
Get-WinEvent -ListLog * | Where-Object RecordCount -gt 0 | Select-Object LogName, RecordCount
Level is 1 critical, 2 error, 3 warning, 4 information. Always filter with -FilterHashtable: it is processed by the event log service itself and is hundreds of times faster than getting every event and then using Where-Object. The old Get-EventLog exists only in Windows PowerShell 5.1.
System information
Get-ComputerInfo | Select-Object CsName, WindowsProductName, OsVersion, CsTotalPhysicalMemory
Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, LastBootUpTime
(Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime # uptime
Get-CimInstance Win32_Processor | Select-Object Name, NumberOfCores
Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" |
Select-Object DeviceID, @{ n = 'FreeGB'; e = { [math]::Round($_.FreeSpace / 1GB, 1) } }, @{ n = 'SizeGB'; e = { [math]::Round($_.Size / 1GB, 1) } }
Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 10 # installed updates
CIM (Get-CimInstance) is the modern way to ask Windows for hardware and operating system data. The older Get-WmiObject does the same job but was removed from PowerShell 7. If you have Windows Update problems, see Fix Windows Update Errors: Reset Update Components, SFC and DISM.
9. Users, groups and Active Directory
Local accounts
Get-LocalUser
New-LocalUser -Name 'helpdesk' -Password (Read-Host -AsSecureString 'Password') -FullName 'Help Desk' -PasswordNeverExpires:$false
Add-LocalGroupMember -Group 'Administrators' -Member 'helpdesk'
Get-LocalGroupMember -Group 'Administrators'
Disable-LocalUser -Name 'helpdesk'
Remove-LocalUser -Name 'helpdesk'
Read-Host -AsSecureString asks for the password without showing it and without leaving it in plain text in your script or history. Never write passwords inside a script.
Active Directory
The ActiveDirectory module comes with the Remote Server Administration Tools (RSAT). On Windows 11: Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0. On a server: Install-WindowsFeature RSAT-AD-PowerShell.
Get-ADUser -Identity jsmith -Properties * # everything about one user
Get-ADUser -Filter "Name -like 'Smith*'" -Properties EmailAddress, LastLogonDate |
Select-Object Name, SamAccountName, EmailAddress, LastLogonDate
Search-ADAccount -LockedOut | Select-Object Name, SamAccountName # who is locked out?
Unlock-ADAccount -Identity jsmith
Set-ADAccountPassword -Identity jsmith -Reset -NewPassword (Read-Host -AsSecureString 'New password')
Set-ADUser jsmith -ChangePasswordAtLogon $true
Disable-ADAccount -Identity jsmith
Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 -UsersOnly | Select-Object Name, LastLogonDate # unused for 90 days
Get-ADGroupMember -Identity 'Finance' | Select-Object Name, SamAccountName
Add-ADGroupMember -Identity 'Finance' -Members jsmith
Get-ADComputer -Filter * -Properties OperatingSystem | Group-Object OperatingSystem
Use -Filter to let the domain controller do the searching. Get-ADUser -Filter * followed by Where-Object downloads every user first and is very slow in large domains.
10. Networking and the web
Test-NetConnection google.com # ping and route check
Test-NetConnection server01 -Port 443 # is TCP port 443 open? (Windows)
Resolve-DnsName example.com -Type MX # DNS lookup (Windows)
Get-NetIPAddress -AddressFamily IPv4 | Select-Object InterfaceAlias, IPAddress, PrefixLength
Get-NetAdapter | Select-Object Name, Status, LinkSpeed, MacAddress
Get-NetRoute -DestinationPrefix 0.0.0.0/0 # the default gateway
Get-DnsClientServerAddress -AddressFamily IPv4
Get-NetTCPConnection -State Listen | Select-Object LocalAddress, LocalPort, OwningProcess |
Sort-Object LocalPort # what is listening? (like netstat -an)
Get-Process -Id 1234 # which program is process 1234?
For deeper DNS work, see DNS Troubleshooting with dig and nslookup.
Windows Firewall
Get-NetFirewallProfile | Select-Object Name, Enabled
New-NetFirewallRule -DisplayName 'Allow HTTPS in' -Direction Inbound -Protocol TCP -LocalPort 443 -Action Allow
Get-NetFirewallRule -DisplayName 'Allow HTTPS in' | Get-NetFirewallPortFilter
Disable-NetFirewallRule -DisplayName 'Allow HTTPS in'
Remove-NetFirewallRule -DisplayName 'Allow HTTPS in'
Web requests and APIs
$r = Invoke-WebRequest https://example.com # the page, status, headers
$r.StatusCode ; $r.Headers['Content-Type']
$data = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell # JSON becomes objects automatically
$data.stargazers_count
# POST JSON with a token (keep tokens out of your script: see section 16)
Invoke-RestMethod -Uri https://api.example.com/items -Method Post -ContentType 'application/json' `
-Headers @{ Authorization = "Bearer $token" } -Body (@{ name = 'test' } | ConvertTo-Json)
Invoke-WebRequest https://example.com/file.zip -OutFile C:\Temp\file.zip # download
The backtick ` at the end of a line continues the command on the next line. It must be the very last character on the line, with no space after it. A cleaner way for many parameters is splatting: put them in a hashtable and pass it with @.
$params = @{
Uri = 'https://api.example.com/items'
Method = 'Post'
ContentType = 'application/json'
Body = (@{ name = 'test' } | ConvertTo-Json)
}
Invoke-RestMethod @params
11. Disks, the registry and scheduled tasks
Storage
Get-Volume | Select-Object DriveLetter, FileSystemLabel, FileSystem,
@{ n = 'FreeGB'; e = { [math]::Round($_.SizeRemaining / 1GB, 1) } },
@{ n = 'SizeGB'; e = { [math]::Round($_.Size / 1GB, 1) } }
Get-Disk
Get-Partition -DiskNumber 0
Get-PSDrive -PSProvider FileSystem
Resize-Partition -DriveLetter D -Size (Get-PartitionSupportedSize -DriveLetter D).SizeMax # grow to use all free space
The registry
Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' | Select-Object ProductName, CurrentBuild
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall' |
Get-ItemProperty | Select-Object DisplayName, DisplayVersion | Sort-Object DisplayName # installed programs
New-Item -Path 'HKCU:\Software\MyApp' -Force
Set-ItemProperty -Path 'HKCU:\Software\MyApp' -Name 'Mode' -Value 'Fast'
New-ItemProperty -Path 'HKCU:\Software\MyApp' -Name 'Count' -Value 3 -PropertyType DWord -Force
Remove-ItemProperty -Path 'HKCU:\Software\MyApp' -Name 'Count'
Back up a key before editing it: reg export "HKLM\SOFTWARE\MyApp" C:\Backup\myapp.reg. Changes under HKLM: need an elevated window.
Scheduled tasks
$action = New-ScheduledTaskAction -Execute 'pwsh.exe' -Argument '-NoProfile -File C:\Scripts\cleanup.ps1'
$trigger = New-ScheduledTaskTrigger -Daily -At 2:30am
Register-ScheduledTask -TaskName 'Nightly cleanup' -Action $action -Trigger $trigger -User 'SYSTEM' -RunLevel Highest
Get-ScheduledTask -TaskName 'Nightly cleanup' | Get-ScheduledTaskInfo # last run time and result
Start-ScheduledTask -TaskName 'Nightly cleanup'
Disable-ScheduledTask -TaskName 'Nightly cleanup'
Unregister-ScheduledTask -TaskName 'Nightly cleanup' -Confirm:$false
Use powershell.exe instead of pwsh.exe if PowerShell 7 is not installed on that machine. -NoProfile makes the task start faster and behave the same on every machine.
12. Remoting: run commands on other computers
PowerShell can run commands on many machines at once, which is where it saves the most time. On Windows it uses WinRM (port 5985 for HTTP, 5986 for HTTPS); PowerShell 7 can also use SSH.
# On the target computer, once, as administrator:
Enable-PSRemoting -Force
# From your computer:
Enter-PSSession -ComputerName srv01 # an interactive session (type Exit-PSSession to leave)
Invoke-Command -ComputerName srv01, srv02, srv03 -ScriptBlock {
Get-Service W32Time | Select-Object Name, Status
}
$s = New-PSSession -ComputerName srv01 # a reusable connection
Invoke-Command -Session $s -ScriptBlock { Get-Process | Sort-Object CPU -Descending | Select-Object -First 3 }
Copy-Item C:\Scripts\fix.ps1 -Destination C:\Scripts\ -ToSession $s
Remove-PSSession $s
Results from Invoke-Command come back with an extra PSComputerName property, so you can see which machine each line came from. To use your local variables on the remote side, write $using:name inside the script block. Inside a domain, remoting works with your normal sign-in. For computers outside a domain you need HTTPS or TrustedHosts, and you should understand the risk before relaxing that setting. Over SSH (PowerShell 7): Enter-PSSession -HostName user@server.
Run in the background and in parallel
$job = Start-Job { Get-ChildItem C:\ -Recurse -File | Measure-Object Length -Sum }
Get-Job ; Receive-Job $job -Wait -AutoRemoveJob # collect the result
# PowerShell 7: process items in parallel
1..10 | ForEach-Object -Parallel { Test-Connection "10.0.0.$_" -Count 1 -TimeoutSeconds 1 -Quiet } -ThrottleLimit 5
13. Writing scripts and functions
When you find yourself repeating commands, save them in a .ps1 file. Run it with .\script.ps1 (the .\ is required: PowerShell does not run files from the current folder unless you say so). If it refuses to start, read the execution policy in section 16.
A function with parameters
function Get-DiskReport {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string[]] $ComputerName,
[ValidateRange(1, 99)]
[int] $WarnBelowPercent = 15
)
foreach ($pc in $ComputerName) {
Get-CimInstance Win32_LogicalDisk -ComputerName $pc -Filter 'DriveType=3' | ForEach-Object {
$freePct = [math]::Round($_.FreeSpace / $_.Size * 100, 1)
[PSCustomObject]@{
Computer = $pc
Drive = $_.DeviceID
FreeGB = [math]::Round($_.FreeSpace / 1GB, 1)
FreePct = $freePct
Warning = $freePct -lt $WarnBelowPercent
}
}
}
}
Get-DiskReport -ComputerName srv01, srv02 | Where-Object Warning | Format-Table
What the pieces do: [CmdletBinding()] turns the function into an “advanced function” that supports -Verbose, -ErrorAction and other common parameters. [Parameter(Mandatory)] makes PowerShell ask for the value if it is missing. [ValidateRange] rejects wrong values before your code runs. The function returns objects (not text), so the caller can filter, sort or export them. Use the approved verbs (Get-Verb lists them) in function names.
Document your function with a comment block, and Get-Help will display it:
<#
.SYNOPSIS
Reports free disk space on one or more computers.
.EXAMPLE
Get-DiskReport -ComputerName srv01 -WarnBelowPercent 20
#>
Script parameters and your profile
# At the top of cleanup.ps1
param(
[string] $Path = 'C:\Temp',
[int] $OlderThanDays = 30
)
Get-ChildItem $Path -File -Recurse | Where-Object LastWriteTime -lt (Get-Date).AddDays(-$OlderThanDays) | Remove-Item -WhatIf
Run it with .\cleanup.ps1 -Path D:\Scratch -OlderThanDays 60. Your profile is a script that runs every time PowerShell starts; its location is in $PROFILE. Create it with New-Item -Path $PROFILE -Force and put your favourite functions and aliases there.
14. Errors, -WhatIf and safe automation
PowerShell has two kinds of errors. A terminating error stops the command and can be caught. A non-terminating error is printed, but the script carries on, and try/catch does not see it. Most cmdlets produce non-terminating errors, so to catch them you must ask for Stop:
try {
$file = Get-Content C:\missing.txt -ErrorAction Stop # without -ErrorAction Stop, catch never runs
'Loaded'
}
catch [System.Management.Automation.ItemNotFoundException] {
"The file does not exist: $($_.Exception.Message)"
}
catch {
"Something else went wrong: $($_.Exception.Message)"
throw # pass the error on to the caller
}
finally {
'This always runs: close files and connections here'
}
$ErrorActionPreference = 'Stop' # make every error in a script terminating (a good habit)
Inside catch, the variable $_ is the error. Useful details: $_.Exception.Message (the text), $_.InvocationInfo.ScriptLineNumber (the line) and $_.ScriptStackTrace.
Test before you do it: -WhatIf and -Confirm
Remove-Item C:\Temp\old\* -Recurse -WhatIf # only says what WOULD be deleted
Stop-Service Spooler -Confirm # asks "Are you sure?" first
Get-ChildItem C:\Temp -Recurse | Where-Object LastWriteTime -lt (Get-Date).AddDays(-30) | Remove-Item -WhatIf
Make -WhatIf your default for anything that deletes or changes. Check the output, then remove the switch. In your own functions, add [CmdletBinding(SupportsShouldProcess)] and wrap the dangerous line in if ($PSCmdlet.ShouldProcess($target, 'Delete')) { ... } to get this behaviour for free.
Logging
Start-Transcript -Path "C:\Logs\cleanup-$(Get-Date -Format yyyyMMdd-HHmm).log"
# ... your script ...
Stop-Transcript
Write-Verbose 'Checking disk...' # shown only when the script runs with -Verbose
Write-Warning 'Disk is 90% full'
Write-Error 'Cannot connect'
Write-Host 'Done' -ForegroundColor Green # for screen messages only; it is not output you can pipe
In a function, return data with the plain output ($obj or Write-Output $obj) and use Write-Host only for messages to the person watching.
15. Modules and the PowerShell Gallery
A module is a package of cmdlets. Windows ships many, and the free PowerShell Gallery has thousands more.
Get-Module -ListAvailable # modules installed on this computer
Import-Module ActiveDirectory # load one (PowerShell also loads it automatically when you call a cmdlet)
Find-Module -Name *Excel* # search the Gallery
Install-Module -Name ImportExcel -Scope CurrentUser # install without administrator rights
Update-Module ImportExcel
Uninstall-Module ImportExcel
Get-Command -Module ImportExcel # what does it contain?
The first time, Windows PowerShell 5.1 asks to install the NuGet provider and to trust the Gallery: answer yes if you accept that source. Install only modules from authors you trust, because a module runs with your rights.
Useful modules
| Module | What it does |
|---|---|
dbatools |
Hundreds of commands for SQL Server: backups, restores, migrations, jobs, permissions |
ImportExcel |
Read and write .xlsx files without installing Excel |
PSWindowsUpdate |
Search and install Windows updates from the command line |
Az |
Manage Microsoft Azure |
Microsoft.Graph |
Manage Microsoft 365 and Entra ID (the old MSOnline and AzureAD modules are retired) |
Pester |
Test your scripts |
PSScriptAnalyzer |
Checks scripts for mistakes and bad style |
PowerShell and SQL Server
With dbatools, tasks that need long T-SQL become one line:
Install-Module dbatools -Scope CurrentUser
Get-DbaDatabase -SqlInstance localhost | Select-Object Name, RecoveryModel, SizeMB, LastFullBackup
Backup-DbaDatabase -SqlInstance localhost -Database SalesDB -Type Full -Path D:\Backup
Test-DbaLastBackup -SqlInstance localhost -Database SalesDB # restores the last backup elsewhere to prove it works
Get-DbaLogin -SqlInstance localhost
Copy-DbaDatabase -Source old01 -Destination new01 -Database SalesDB -BackupRestore -SharedPath \\fileserver\sqlbackup
It complements the T-SQL in our articles on backing up and restoring SQL Server and Agent jobs and alerts.
16. Credentials, execution policy and security
Execution policy
The execution policy decides which scripts may run. It is a safety belt against running a script by accident, not a security boundary: anyone who can type a command can get around it.
Get-ExecutionPolicy -List
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser # local scripts run; downloaded ones must be signed
Unblock-File .\downloaded-script.ps1 # you have read it and trust it
pwsh -ExecutionPolicy Bypass -File .\task.ps1 # one-off for a trusted script (e.g. in a scheduled task)
| Policy | Meaning |
|---|---|
Restricted |
No scripts at all (default on Windows 10 and 11) |
RemoteSigned |
Your own scripts run, scripts from the internet need a trusted signature (default on Windows Server) |
AllSigned |
Every script must be signed |
Bypass |
Nothing is blocked, no warnings |
Passwords and secrets
$cred = Get-Credential # pops up a user name and password prompt
Invoke-Command -ComputerName srv01 -Credential $cred -ScriptBlock { whoami }
# Save a credential for the same user on the same computer (Windows encrypts it with your account)
$cred | Export-Clixml C:\Secure\svc.xml
$cred = Import-Clixml C:\Secure\svc.xml
An exported credential file can only be opened by the same Windows user on the same computer, so copying it elsewhere does not work (and does not leak the password). For anything shared by a team, use the Microsoft.PowerShell.SecretManagement module with a vault such as Azure Key Vault. Never type a password or token into a script, and do not turn a SecureString back into plain text unless you must.
Read before you run
Never paste a command from a website straight into an elevated window. In particular, be careful with one-liners that download and run something: iex (irm https://...) executes whatever that web address returns, with your rights. Download the script, read it, then run it. Also check the signature of scripts you receive: Get-AuthenticodeSignature .\script.ps1.
17. Ready-made recipes
Each recipe is short, uses only what you have learned, and is safe to adapt. Run the ones that delete things with -WhatIf first.
Servers with low disk space
$servers = Get-Content C:\Scripts\servers.txt
Invoke-Command -ComputerName $servers -ScriptBlock {
Get-Volume | Where-Object { $_.DriveType -eq 'Fixed' -and $_.SizeRemaining / $_.Size -lt 0.15 } |
Select-Object DriveLetter, @{ n = 'FreeGB'; e = { [math]::Round($_.SizeRemaining / 1GB, 1) } }
} | Select-Object PSComputerName, DriveLetter, FreeGB
Clean up old files
$limit = (Get-Date).AddDays(-30)
Get-ChildItem 'D:\Logs' -File -Recurse | Where-Object LastWriteTime -lt $limit | Remove-Item -WhatIf
Services that should be running but are not
Get-Service | Where-Object { $_.StartType -eq 'Automatic' -and $_.Status -ne 'Running' } |
Select-Object Name, DisplayName, Status
Rename many files
Get-ChildItem C:\Photos -Filter *.jpg | Rename-Item -NewName { $_.Name -replace '^IMG_', 'Holiday-' } -WhatIf
Get-ChildItem C:\Photos -Filter *.jpg | ForEach-Object -Begin { $n = 1 } -Process { Rename-Item $_ -NewName ('Trip-{0:000}.jpg' -f $n++) }
The format operator -f fills {0:000} with a number padded to three digits.
Certificates that expire soon
Get-ChildItem Cert:\LocalMachine\My | Where-Object NotAfter -lt (Get-Date).AddDays(30) |
Select-Object Subject, NotAfter, Thumbprint
Ping a range of addresses
1..254 | ForEach-Object -Parallel {
$ip = "192.168.1.$_"
if (Test-Connection $ip -Count 1 -TimeoutSeconds 1 -Quiet) { $ip }
} -ThrottleLimit 50 # PowerShell 7
Inactive Active Directory accounts to a CSV
Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 -UsersOnly |
Select-Object Name, SamAccountName, LastLogonDate, Enabled |
Export-Csv C:\Reports\inactive-users.csv -NoTypeInformation
An HTML report by email
$html = Get-Service | Where-Object Status -eq 'Stopped' | Select-Object Name, DisplayName | ConvertTo-Html -Title 'Stopped services' | Out-String
Send-MailMessage -To admin@example.com -From alerts@example.com -Subject 'Stopped services' -Body $html -BodyAsHtml -SmtpServer smtp.example.com
Send-MailMessage is marked obsolete because it does not support modern authentication. It still works with a plain internal relay. For Microsoft 365, use the Microsoft Graph module instead.
18. PowerShell for people who know Bash
If you read our Linux commands guide, this table connects the two worlds. PowerShell 7 even runs on Linux and has aliases such as ls and cat, but they run the PowerShell cmdlets, so the options are different.
| Bash | PowerShell |
|---|---|
ls -la |
Get-ChildItem -Force |
cd, pwd |
Set-Location, Get-Location |
cat file, tail -f file |
Get-Content file, Get-Content file -Tail 10 -Wait |
grep text file |
Select-String -Path file -Pattern text |
find . -name "*.log" |
Get-ChildItem -Recurse -Filter *.log |
cp, mv, rm -r |
Copy-Item, Move-Item, Remove-Item -Recurse |
ps aux, kill |
Get-Process, Stop-Process |
systemctl status x |
Get-Service x |
sort | uniq -c |
Group-Object (add Sort-Object Count) |
wc -l |
Measure-Object -Line or .Count |
head -n 5 |
Select-Object -First 5 |
awk '{print $1}' |
Select-Object -ExpandProperty Name (properties instead of columns) |
curl |
Invoke-WebRequest, Invoke-RestMethod (in 5.1, curl is an alias for this) |
export VAR=1 |
$env:VAR = '1' |
cmd1 && cmd2 |
cmd1 && cmd2 (PowerShell 7 only) |
sudo |
Start an elevated window, or Start-Process pwsh -Verb RunAs |
The big difference to remember: Bash pipes text, PowerShell pipes objects. Where you would use cut or awk, you use Select-Object.
19. Good habits and common mistakes
- Look at the object first. Pipe anything unfamiliar into
Get-MemberorSelect-Object *before writing a filter. - Filter early. Use the cmdlet’s own
-Filteror-Nameparameter instead of fetching everything and then usingWhere-Object. It is far faster, especially for Active Directory, event logs and remote computers. - Format last.
Format-TableandFormat-Listbelong at the very end of a pipeline, never beforeExport-Csvor another command. - Use
-WhatIffirst for every command that deletes, stops or changes. Remove it only after reading the output. - Return objects, not text. Functions that output objects can be sorted, filtered and exported by whoever uses them.
- Use full cmdlet names and parameter names in scripts. Aliases and shortened parameters are for typing, not for sharing.
- Put
$nullon the left in comparisons and use-ErrorAction Stopinsidetryblocks. - Quote paths that contain spaces and use
-LiteralPathwhen a name contains[or]. - Keep secrets out of scripts and out of version control.
- Test on a copy of the data or a test machine before you run something against production.
Quick answers
Is PowerShell only for Windows? No. PowerShell 7 runs on Windows, Linux and macOS. Some cmdlets (those that manage Windows features, such as the services, registry and event logs) work only on Windows.
Should I learn PowerShell or Python? For managing Windows, Active Directory, Microsoft 365, Azure and SQL Server, PowerShell is the natural first choice because the tools are built for it. Python is better for general programming, data analysis and web work. Many administrators know both.
Why does my script work in the console but not as a scheduled task? The task runs under another account, with a different profile, no mapped drives and a different working folder. Use full paths, -NoProfile, UNC paths (\\server\share) instead of drive letters, and log with Start-Transcript so you can see what happened.
Where do I learn more? Use Get-Help <command> -Examples every day, read the about_ help articles (Get-Help about_*), and the official documentation at learn.microsoft.com/powershell. For a faster start, see our shorter list of 10 PowerShell one-liners every Windows admin should know.
More tutorials like this
Why Did My Windows PC Restart or Crash? Find the Answer in Event Viewer and PowerShell
Find out why Windows restarted: the key event IDs (41, 6008, 1074, 1001), PowerShell commands to read them, and what to fix for each…
Bash Scripting for Beginners: Variables, Loops, Functions and Exit Codes
Learn Bash scripting from your first script to a safe backup script: variables, quoting, loops, functions, exit codes and set -euo pipefail, with real…
Fix Windows Update Errors: Reset Update Components, SFC and DISM
Windows Update stuck or failing with an error code? Run the built-in troubleshooter, repair system files with DISM and SFC, and reset the update…



