PowerShell commands cheat sheet

Quick Reference

Cmdlet Structure
Verb-Noun
Pipeline Operator
|
Help System
Get-Help, Get-Command, Get-Member
Current Version
$PSVersionTable.PSVersion
Profile Location
$PROFILE
Execution Policy
Get-ExecutionPolicy

Core Verb Conventions

PowerShell enforces approved verbs for cmdlets. Knowing the common verbs lets you guess cmdlet names before looking them up.

VerbMeaningExample
GetRetrieve data, no side effectsGet-Process
SetChange existing resourceSet-Item
NewCreate a new resourceNew-Item
RemoveDelete a resourceRemove-Item
AddAdd to existing resourceAdd-Content
StartBegin an operationStart-Service
StopEnd an operationStop-Process
RestartStop then startRestart-Service
Enable / DisableActivate or deactivateEnable-NetAdapter
TestVerify somethingTest-Path
InvokeRun a command or scriptInvoke-Command
Export / ImportSerialize / deserialize dataExport-Csv
SelectChoose specific properties or objectsSelect-Object
WhereFilter objectsWhere-Object
SortReorder objectsSort-Object
FormatChange display formatFormat-Table
Aliases: Many cmdlets have shorter aliases. ls, dirGet-ChildItem. cdSet-Location. cat, typeGet-Content. psGet-Process. Use full cmdlet names in scripts — aliases are for interactive use only.

Help & Discovery

The built-in help system is PowerShell’s most powerful feature. Learn these first.

CommandWhat It Does
Get-Help Get-ProcessShow help for a cmdlet
Get-Help Get-Process -FullFull help with all parameters and examples
Get-Help Get-Process -ExamplesShow usage examples only
Get-Help Get-Process -OnlineOpen official docs in browser
Get-Help *service*Find all cmdlets with “service” in name
Update-HelpDownload latest help files from internet
Get-Command *process*Find cmdlets matching a pattern
Get-Command -Verb Get -Noun *network*Find cmdlets by verb and noun
Get-Command -Module ActiveDirectoryList all cmdlets in a module
Get-Process | Get-MemberShow all properties and methods of an object
Get-Process | Get-Member -MemberType PropertyShow properties only
$PSVersionTableShow PowerShell version and environment
Get-Module -ListAvailableList all installed modules
Import-Module ActiveDirectoryLoad a module into current session
Find-Module -Name *SQL*Search PowerShell Gallery for modules
Install-Module -Name PSReadLineInstall module from PowerShell Gallery

Filesystem & Files

CommandWhat It Does
Get-LocationShow current directory (pwd)
Set-Location C:\TempChange directory (cd)
Set-Location ..Go up one directory
Get-ChildItemList files and folders (ls / dir)
Get-ChildItem -RecurseList recursively including subdirectories
Get-ChildItem -Filter *.logList only .log files
Get-ChildItem -HiddenShow hidden files
New-Item -ItemType File -Name test.txtCreate a new empty file
New-Item -ItemType Directory -Name logsCreate a new folder
Copy-Item file.txt C:\Backup\Copy file to destination
Copy-Item C:\Source -Destination C:\Dest -RecurseCopy folder recursively
Move-Item file.txt C:\Archive\Move file
Rename-Item old.txt new.txtRename file or folder
Remove-Item file.txtDelete file
Remove-Item C:\Temp -Recurse -ForceDelete folder and contents without confirmation
Test-Path C:\Logs\app.logCheck if path exists (returns True/False)
Get-Content file.txtRead file contents (cat / type)
Get-Content file.txt -Tail 50Read last 50 lines
Get-Content file.txt -WaitTail a file live (like tail -f)
Set-Content file.txt "Hello"Write text to file (overwrites)
Add-Content file.txt "New line"Append text to file
"Hello" | Out-File file.txtWrite pipeline output to file
Get-Item file.txt | Select-Object Name, Length, LastWriteTimeShow file metadata
(Get-Item file.txt).Length / 1MBGet file size in MB

Processes & Services

Processes

CommandWhat It Does
Get-ProcessList all running processes
Get-Process -Name chromeGet specific process by name
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10Top 10 processes by CPU
Get-Process | Sort-Object WorkingSet -Descending | Select-Object -First 10Top 10 processes by memory
Stop-Process -Name notepadKill process by name
Stop-Process -Id 1234Kill process by PID
Stop-Process -Name chrome -ForceForce kill without confirmation
Start-Process notepad.exeStart a process
Start-Process cmd.exe -Verb RunAsStart process as Administrator
(Get-Process chrome | Measure-Object WorkingSet -Sum).Sum / 1MBTotal memory used by all Chrome processes in MB

Services

CommandWhat It Does
Get-ServiceList all services and their status
Get-Service -Name wuauservGet specific service (Windows Update)
Get-Service | Where-Object Status -eq 'Running'List only running services
Get-Service | Where-Object StartType -eq 'Automatic' | Where-Object Status -eq 'Stopped'Find auto-start services that are stopped
Start-Service -Name SpoolerStart a service
Stop-Service -Name SpoolerStop a service
Restart-Service -Name SpoolerRestart a service
Restart-Service -Name Spooler -ForceRestart even if dependent services are running
Set-Service -Name Spooler -StartupType DisabledChange service startup type
Set-Service -Name Spooler -StartupType AutomaticSet service to auto-start

Networking

CommandWhat It Does
Get-NetIPAddressShow all IP addresses on all interfaces
Get-NetIPAddress -AddressFamily IPv4Show IPv4 addresses only
Get-NetAdapterList network adapters and status
Get-NetAdapter | Where-Object Status -eq 'Up'List only connected adapters
Get-NetRouteShow routing table
Get-NetRoute -DestinationPrefix "0.0.0.0/0"Show default gateway
Get-DnsClientServerAddressShow configured DNS servers
Resolve-DnsName google.comDNS lookup (like nslookup)
Resolve-DnsName google.com -Type MXLook up MX records
Test-NetConnection google.comTest connectivity (ping + traceroute info)
Test-NetConnection google.com -Port 443Test TCP port connectivity
Test-NetConnection 8.8.8.8 -TraceRouteRun traceroute
Get-NetTCPConnectionList all TCP connections and listeners
Get-NetTCPConnection -State ListenShow listening ports only
Get-NetTCPConnection -LocalPort 80Find what is using port 80
Get-NetTCPConnection | Where-Object State -eq 'Established' | Measure-ObjectCount established connections
Clear-DnsClientCacheFlush DNS cache
Get-DnsClientCacheView current DNS cache entries
Enable-NetAdapter -Name "Ethernet"Enable a network adapter
Disable-NetAdapter -Name "Ethernet" -Confirm:$falseDisable a network adapter without prompt

System Information

CommandWhat It Does
Get-ComputerInfoComprehensive system information
Get-ComputerInfo | Select-Object CsName, WindowsVersion, OsArchitectureHostname, Windows version, architecture
$env:COMPUTERNAMEGet hostname quickly
[System.Environment]::OSVersionOS version details
Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, BuildNumberOS name and build number
Get-CimInstance Win32_ComputerSystem | Select-Object TotalPhysicalMemoryTotal RAM in bytes
(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GBTotal RAM in GB
Get-CimInstance Win32_Processor | Select-Object Name, NumberOfCores, NumberOfLogicalProcessorsCPU info
Get-CimInstance Win32_LogicalDisk | Select-Object DeviceID, Size, FreeSpaceDisk size and free space
Get-CimInstance Win32_LogicalDisk | Select-Object DeviceID, @{N='FreeGB';E={[math]::Round($_.FreeSpace/1GB,2)}}, @{N='SizeGB';E={[math]::Round($_.Size/1GB,2)}}Disk info in GB
Get-CimInstance Win32_BIOS | Select-Object Manufacturer, SMBIOSBIOSVersionBIOS information
Get-HotFix | Sort-Object InstalledOn -DescendingList installed Windows updates
Get-HotFix -Id KB5034441Check if specific KB is installed
Get-DateCurrent date and time
(Get-CimInstance Win32_OperatingSystem).LastBootUpTimeLast system boot time
(Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTimeSystem uptime
$env:USERNAMECurrent user
[Security.Principal.WindowsIdentity]::GetCurrent().NameCurrent user with domain
whoami /groupsList group memberships of current user

Local Users & Groups

CommandWhat It Does
Get-LocalUserList all local user accounts
Get-LocalUser | Where-Object Enabled -eq $trueList enabled users only
New-LocalUser -Name "svc_backup" -NoPasswordCreate local user without password
Set-LocalUser -Name "svc_backup" -Password (Read-Host -AsSecureString)Set password for local user
Disable-LocalUser -Name "Guest"Disable a local user
Enable-LocalUser -Name "Administrator"Enable a local user
Remove-LocalUser -Name "olduser"Delete a local user
Get-LocalGroupList all local groups
Get-LocalGroupMember -Group "Administrators"List members of Administrators group
Add-LocalGroupMember -Group "Administrators" -Member "svc_backup"Add user to local group
Remove-LocalGroupMember -Group "Administrators" -Member "olduser"Remove user from local group
Active Directory: For domain user/group management, use the ActiveDirectory module (Import-Module ActiveDirectory). Cmdlets follow the same pattern: Get-ADUser, New-ADUser, Add-ADGroupMember, etc.

Event Logs

CommandWhat It Does
Get-EventLog -ListList all classic event logs
Get-EventLog -LogName System -Newest 50Get last 50 System log entries
Get-EventLog -LogName Application -EntryType Error -Newest 20Get last 20 Application errors
Get-EventLog -LogName System -EntryType Error,Warning -After (Get-Date).AddHours(-24)Errors and warnings from last 24 hours
Get-WinEvent -LogName System -MaxEvents 100Get events using newer API (supports all logs)
Get-WinEvent -LogName Security -MaxEvents 50Get Security log events (requires admin)
Get-WinEvent -FilterHashtable @{LogName='System'; Level=2; StartTime=(Get-Date).AddDays(-1)}Filter by log, severity (2=Error), and time
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625} -MaxEvents 20Get failed login attempts (Event ID 4625)
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624} -MaxEvents 20Get successful logins (Event ID 4624)
Get-WinEvent -LogName System | Where-Object {$_.Message -like "*disk*"}Search event messages for keyword
Clear-EventLog -LogName ApplicationClear an event log (requires admin)
Event IDLogMeaning
4624SecuritySuccessful logon
4625SecurityFailed logon attempt
4648SecurityLogon with explicit credentials (RunAs)
4720SecurityUser account created
4740SecurityUser account locked out
4776SecurityNTLM authentication attempt
7034SystemService crashed unexpectedly
7036SystemService entered started/stopped state
1102SecurityAudit log cleared (investigate immediately)
41SystemSystem rebooted without clean shutdown (crash)

Pipeline & Object Manipulation

The pipeline passes objects, not text. This is what makes PowerShell fundamentally different from Bash.

CommandWhat It Does
Get-Process | Where-Object CPU -gt 10Filter: processes using more than 10 CPU seconds
Get-Process | Where-Object {$_.WorkingSet -gt 100MB}Filter with script block (more complex conditions)
Get-Service | Select-Object Name, Status, StartTypeSelect specific properties only
Get-Process | Select-Object -First 5Take first 5 objects
Get-Process | Select-Object -Last 5Take last 5 objects
Get-Process | Sort-Object CPU -DescendingSort by property descending
Get-Process | Sort-Object Name | Select-Object Name, CPU | Format-TableSort, select, display as table
Get-Process | Measure-Object WorkingSet -Sum -Average -MaxAggregate statistics on a property
Get-Process | Group-Object CompanyGroup objects by property value
Get-Service | Select-Object Name, Status | Export-Csv services.csv -NoTypeInformationExport to CSV
Import-Csv users.csv | ForEach-Object { New-LocalUser $_.Name }Import CSV and process each row
Get-Process | ConvertTo-Json | Out-File procs.jsonExport to JSON
Get-Process | Out-GridViewDisplay in interactive GUI grid (Windows only)
Get-Process | Format-List *Show all properties as a list
Get-Process | Format-Table Name, CPU, WorkingSet -AutoSizeCustom table with auto-sized columns
1..10 | ForEach-Object { Write-Output "Item $_" }Loop over a range with ForEach-Object
Get-ChildItem *.log | ForEach-Object { Remove-Item $_ }Delete each file matching a pattern
"a","b","c" | ForEach-Object { $_.ToUpper() }Transform each string in an array
Where-Object shorthand: Where-Object Status -eq 'Running' is equivalent to Where-Object {$_.Status -eq 'Running'}. The simplified syntax works for single conditions. Use the script block form ({}) when you need -and, -or, or more complex logic.

Remoting & Remote Execution

CommandWhat It Does
Enable-PSRemoting -ForceEnable WinRM and PSRemoting on the machine
Test-WSMan -ComputerName server01Test if WinRM is reachable on remote host
Enter-PSSession -ComputerName server01Start interactive remote session
Enter-PSSession -ComputerName server01 -Credential (Get-Credential)Connect with alternate credentials
Exit-PSSessionEnd interactive remote session
Invoke-Command -ComputerName server01 -ScriptBlock { Get-Service }Run a command on a remote machine
Invoke-Command -ComputerName server01,server02 -ScriptBlock { hostname }Run command on multiple machines in parallel
Invoke-Command -ComputerName server01 -FilePath C:\Scripts\deploy.ps1Run a local script on a remote machine
$s = New-PSSession -ComputerName server01Create a persistent session
Invoke-Command -Session $s -ScriptBlock { $result = Get-Process }Run command in persistent session (keeps state)
Remove-PSSession $sClose a persistent session
Get-PSSessionList all open sessions
Copy-Item C:\file.txt -ToSession $s -Destination C:\Temp\Copy file to remote session
Invoke-Command -ComputerName (Get-Content servers.txt) -ScriptBlock { Restart-Service Spooler }Run command on list of servers from file
WinRM prerequisite: PSRemoting requires WinRM to be running on the target machine and a firewall rule allowing port 5985 (HTTP) or 5986 (HTTPS). In a domain environment this is often configured via GPO. On workgroup machines you may also need to add the remote machine to the TrustedHosts list.

Scripting Essentials

Variables & Types

SyntaxMeaning
$name = "server01"String variable
$count = 42Integer variable
[int]$port = "443"Typed variable — coerces string to int
$servers = @("srv1","srv2","srv3")Array
$servers.CountArray length
$map = @{Name="web01"; IP="10.0.0.1"}Hashtable (key-value)
$map["Name"] or $map.NameAccess hashtable value
$nullNull / empty value
$true / $falseBoolean values
"Server: $name port $port"String interpolation (double quotes only)
'Literal $name'Literal string — variables NOT expanded

Control Flow

SyntaxMeaning
if ($x -gt 5) { ... } elseif ($x -eq 5) { ... } else { ... }If/elseif/else
foreach ($item in $collection) { ... }Foreach loop
for ($i = 0; $i -lt 10; $i++) { ... }For loop
while ($condition) { ... }While loop
do { ... } while ($condition)Do-while (runs at least once)
switch ($val) { "a" { ... } "b" { ... } default { ... } }Switch statement
breakExit loop
continueSkip to next iteration
return $valueReturn value from function

Comparison Operators

OperatorMeaningExample
-eq / -neEqual / not equal$x -eq 5
-gt / -ltGreater than / less than$x -gt 10
-ge / -leGreater or equal / less or equal$x -ge 0
-likeWildcard match$s -like "web*"
-notlikeWildcard non-match$s -notlike "*test*"
-matchRegex match$s -match "^\d{3}"
-containsArray contains value$arr -contains "admin"
-inValue is in array"admin" -in $arr
-and / -or / -notLogical operators$a -and $b

Error Handling

Syntax / CommandMeaning
try { ... } catch { ... } finally { ... }Structured error handling block
catch [System.IO.FileNotFoundException] { ... }Catch specific exception type
$_.Exception.MessageGet error message inside catch block
$ErrorActionPreference = 'Stop'Make all errors terminating (catchable)
Get-Item missing.txt -ErrorAction SilentlyContinueSuppress errors for this command
Get-Item missing.txt -ErrorAction StopForce error to be terminating
$Error[0]Last error that occurred
Write-Error "Something went wrong"Write a non-terminating error
throw "Fatal error"Throw a terminating error
ErrorActionPreference: By default, many PowerShell errors are non-terminating — they display an error message but the script continues. Set $ErrorActionPreference = 'Stop' at the top of production scripts so that unexpected errors don’t silently pass through.

Execution Policy & Security

CommandWhat It Does
Get-ExecutionPolicyShow current execution policy
Get-ExecutionPolicy -ListShow execution policy for all scopes
Set-ExecutionPolicy RemoteSigned -Scope CurrentUserAllow local scripts; require signing for downloaded scripts
Set-ExecutionPolicy Bypass -Scope ProcessBypass policy for current session only (not persistent)
Unblock-File -Path .\script.ps1Remove “downloaded from internet” block from file
Get-AuthenticodeSignature script.ps1Check if a script is digitally signed
PolicyMeaningRecommended For
RestrictedNo scripts allowedDefault on Windows clients
AllSignedAll scripts must be signedHigh-security environments
RemoteSignedLocal scripts run freely; downloaded scripts need signingServers and admin workstations
UnrestrictedAll scripts run (prompts for downloaded)Development only
BypassNo restrictions, no promptsAutomation pipelines (CI/CD)
Common mistake: Running Set-ExecutionPolicy Unrestricted or Bypass machine-wide (-Scope LocalMachine) to fix a script that won’t run. Instead, use -Scope CurrentUser or -Scope Process to limit the change, or use Unblock-File on the specific script.

FAQ

What is the difference between PowerShell and Windows PowerShell?
Windows PowerShell (5.1) is built into Windows, based on .NET Framework, and will not receive new features — only security fixes. PowerShell 7+ (formerly PowerShell Core) is cross-platform (Windows, Linux, macOS), based on .NET 6+, and is the actively developed version. For new scripts, target PowerShell 7. Both can be installed side-by-side. Check your version with $PSVersionTable.PSVersion.
What is the difference between Get-WinEvent and Get-EventLog?
Get-EventLog is older and only works with classic Windows event logs (Application, System, Security). Get-WinEvent works with all event logs including modern ETW-based logs, supports powerful hash-based filtering, and performs much better on large logs. Use Get-WinEvent for new scripts — Get-EventLog is deprecated in PowerShell 7.
How do I run a script that won’t execute due to execution policy?
Three safe options: (1) Set-ExecutionPolicy RemoteSigned -Scope CurrentUser — persistent change for your user only. (2) Unblock-File .\script.ps1 — removes the internet-downloaded flag from this specific file. (3) powershell.exe -ExecutionPolicy Bypass -File script.ps1 — bypasses policy for this one run only without changing settings. Avoid machine-wide unrestricted policies.
What is the difference between Write-Host, Write-Output, and Write-Verbose?
Write-Output sends objects to the pipeline — use this in functions and scripts to return data. Write-Host writes directly to the console and bypasses the pipeline — it cannot be captured or redirected, making it unsuitable for scripts meant to be composed. Write-Verbose writes to the verbose stream, only visible when -Verbose flag is used or $VerbosePreference = 'Continue' is set — ideal for debug/progress messages in reusable scripts.
How do I find which process is using a specific port?
Get-NetTCPConnection -LocalPort 80 | Select-Object LocalAddress, LocalPort, State, OwningProcess gives you the PID. Then use Get-Process -Id <PID> to find the process name. You can combine them: Get-NetTCPConnection -LocalPort 80 | ForEach-Object { Get-Process -Id $_.OwningProcess }.
How do I run a PowerShell command as Administrator without opening a new window?
From a non-admin session, you cannot elevate a running process — Windows requires a new elevated process. The pattern is: Start-Process powershell.exe -Verb RunAs -ArgumentList "-Command & { ... }". This opens a UAC prompt and runs the command in a new elevated window. For scripting without UI, consider creating a scheduled task that runs as SYSTEM, or use a deployment tool.