$x = 42Assign a value to a variable.
A massive searchable, copy-ready reference for PowerShell, Windows administration, automation, networking, services, Active Directory, remoting, registry, event logs, storage, scripting, and more.
$x = 42Assign a value to a variable.
$name = 'Ada'Assign a string.
$enabled = $trueAssign a Boolean value.
$nothing = $nullRepresent no value.
Write-Output 'Hello'Write an object to the pipeline.
Write-Host 'Hello'Write directly to the host display.
Read-Host 'Enter name'Read text input from the user.
[int]$count = 5Declare a typed variable.
$a, $b = 1, 2Assign multiple values.
$a, $b = $b, $aSwap values.
$env:COMPUTERNAMERead an environment variable.
$PSVersionTableShow PowerShell version information.
Get-VariableList variables in the current scope.
Remove-Variable xRemove a variable.
Clear-Variable xClear a variable's value.
Get-Help Get-ProcessShow help for a command.
Get-Help Get-Process -FullShow full help.
Get-Help Get-Process -ExamplesShow usage examples.
Get-Help about_Comparison_OperatorsOpen conceptual help.
Get-CommandList available commands.
Get-Command *service*Find commands by name pattern.
Get-Command -Noun ServiceFind commands by noun.
Get-Command -Verb GetFind commands by verb.
Get-MemberInspect properties and methods of pipeline objects.
Get-AliasList aliases.
Get-Alias dirShow what an alias maps to.
Set-Alias ll Get-ChildItemCreate an alias for the current session.
Update-HelpDownload updated help content.
Get-Content file.txtRead a text file.
Get-Content file.txt -First 10Read the first 10 lines.
Get-Content file.txt -Tail 20Read the last 20 lines.
Get-Content file.txt -WaitFollow a growing file.
Set-Content file.txt 'hello'Overwrite a text file.
Add-Content file.txt 'more'Append text to a file.
'hello' | Out-File file.txtWrite pipeline output to a file.
'hello' | Out-File file.txt -AppendAppend pipeline output.
Get-Content file.txt -RawRead the whole file as one string.
Select-String -Path file.txt -Pattern 'error'Search text in a file.
Select-String -Path *.log -Pattern 'failed' -CaseSensitiveSearch multiple files.
Get-Process | Sort-Object CPU -DescendingSort objects by CPU usage.
Get-Process | Select-Object Name, CPU, IdSelect specific properties.
Get-Service | Where-Object Status -eq 'Running'Filter objects by property.
Get-Process | Where-Object {$_.CPU -gt 100}Filter with a script block.
Get-Process | ForEach-Object {$_.Name}Process each pipeline object.
Get-Process | Group-Object ProcessNameGroup objects by property.
Get-Process | Measure-ObjectCount objects.
Get-Process | Measure-Object CPU -Sum -AverageAggregate a numeric property.
Get-Process | Tee-Object processes.txtSave and pass pipeline output.
Get-Process | Format-Table Name, Id, CPU -AutoSizeDisplay objects as a table.
Get-Service | Format-List *Display properties as a list.
Get-Process | Out-GridViewView objects in an interactive grid on supported systems.
$text = 'hello'Create a single-quoted string.
$text = "Hello $name"Create an expandable string.
"Value: $($obj.Name)"Embed an expression in a string.
$text.LengthGet string length.
$text.ToUpper()Convert to uppercase.
$text.ToLower()Convert to lowercase.
$text.Trim()Remove surrounding whitespace.
$text.Replace('old','new')Replace text.
$text.Split(',')Split a string.
-join ('a','b','c')Join values without a separator.
('a','b','c') -join ','Join values with commas.
$text -match 'error'Regex match.
$text -replace 'old','new'Regex-based replacement.
$text -like '*admin*'Wildcard comparison.
$text -contains 'x'Check collection membership.
'x' -in $itemsCheck whether a value is in a collection.
$items = @(1,2,3)Create an array.
$items[0]Get the first array item.
$items[-1]Get the last array item.
$items[1..3]Get a range of array items.
$items += 4Append to an array.
$items.CountGet array length.
$items | Sort-Object -UniqueReturn unique sorted values.
$hash = @{Name='Ada'; Age=18}Create a hashtable.
$hash['Name']Read a hashtable value.
$hash.NameRead a key using property syntax.
$hash['Email']='[email protected]'Add or update a hashtable key.
$hash.Remove('Age')Remove a hashtable key.
$hash.KeysList keys.
$hash.ValuesList values.
[ordered]@{Name='Ada'; Age=18}Create an ordered hashtable.
if ($x -gt 0) { 'positive' }Basic if statement.
if ($x -gt 0) { } else { }if/else.
if ($x -gt 0) { } elseif ($x -eq 0) { } else { }if/elseif/else.
$status = if ($age -ge 18) {'adult'} else {'minor'}Assign from an if expression.
switch ($value) { 'A' {'Alpha'} default {'Other'} }Switch statement.
switch -Regex ($text) { '^ERR' {'Error'} }Regex switch.
if ($null -eq $value) { }Check for null.
if (-not $items) { }Check a falsy/empty value.
foreach ($item in $items) { $item }Loop over a collection.
$items | ForEach-Object { $_ }Pipeline-style iteration.
for ($i=0; $i -lt 10; $i++) { $i }Classic for loop.
while ($condition) { }Repeat while a condition is true.
do { } while ($condition)Run once, then repeat while true.
do { } until ($condition)Run until a condition becomes true.
breakExit the nearest loop or switch.
continueSkip to the next loop iteration.
function Get-Greeting { param($Name) "Hello $Name" }Define a simple function.
function Add-Numbers { param([int]$A,[int]$B) $A+$B }Function with typed parameters.
function Test-Thing { [CmdletBinding()] param([string]$Name) }Create an advanced function.
param([Parameter(Mandatory)] [string]$Name)Require a parameter.
param([ValidateSet('Dev','Prod')] [string]$Mode)Restrict allowed parameter values.
return $valueReturn a value.
$argsAccess unbound arguments.
$PSBoundParametersInspect explicitly bound parameters.
Get-Command MyFunction -SyntaxShow function syntax.
$global:x = 1Create a global-scope variable.
$script:x = 1Create a script-scope variable.
$local:x = 1Create a local-scope variable.
Get-Variable -Scope GlobalList global variables.
$PROFILEShow the current user's PowerShell profile path.
Test-Path $PROFILECheck whether the profile exists.
New-Item -ItemType File -Path $PROFILE -ForceCreate a profile file.
notepad $PROFILEOpen the profile in Notepad on Windows.
try { risky } catch { $_ }Catch terminating errors.
try { } catch [System.IO.IOException] { }Catch a specific exception type.
try { } finally { cleanup }Always run cleanup.
throw 'Something failed'Raise an exception.
$Error[0]View the most recent error.
$Error.Clear()Clear the error collection.
$ErrorActionPreference = 'Stop'Make non-terminating errors terminate.
Get-Item missing -ErrorAction SilentlyContinueOverride error behavior for one command.
Write-Error 'Failure'Write an error record.
Write-Warning 'Warning'Write a warning.
Write-Verbose 'Details'Write verbose output.
Write-Debug 'Debug'Write debug output.
Get-ProcessList running processes.
Get-Process powershellGet processes by name.
Get-Process -Id 1234Get a process by PID.
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10Show top CPU-consuming processes.
Stop-Process -Id 1234Stop a process.
Stop-Process -Name notepad -ForceForce-stop processes by name.
Start-Process notepad.exeStart a process.
Start-Process powershell -Verb RunAsStart a process elevated.
Start-Process cmd -ArgumentList '/c ipconfig'Start a process with arguments.
Wait-Process -Name notepadWait for a process to exit.
Get-ServiceList services.
Get-Service SpoolerGet one service.
Get-Service | Where-Object Status -eq 'Running'List running services.
Start-Service SpoolerStart a service.
Stop-Service SpoolerStop a service.
Restart-Service SpoolerRestart a service.
Suspend-Service ServiceNamePause a service if supported.
Resume-Service ServiceNameResume a paused service.
Set-Service Spooler -StartupType AutomaticSet service startup type.
Get-CimInstance Win32_ServiceQuery detailed service information.
Get-ComputerInfoDisplay broad system information.
Get-CimInstance Win32_OperatingSystemShow OS information.
Get-CimInstance Win32_ComputerSystemShow computer system information.
Get-CimInstance Win32_ProcessorShow CPU information.
Get-CimInstance Win32_PhysicalMemoryShow installed memory modules.
Get-CimInstance Win32_BIOSShow BIOS information.
Get-CimInstance Win32_BaseBoardShow motherboard information.
Get-CimInstance Win32_LogicalDiskShow logical disks.
Get-CimInstance Win32_DiskDriveShow physical disks.
Get-HotFixList installed Windows hotfixes.
systeminfoRun the classic Windows systeminfo command.
Get-NetIPConfigurationShow interface IP configuration.
Get-NetIPAddressList IP addresses.
Get-NetAdapterList network adapters.
Get-NetAdapter | Where-Object Status -eq 'Up'Show active adapters.
Get-NetRouteShow routing table entries.
Get-NetNeighborShow neighbor/ARP information.
Test-Connection 8.8.8.8Send ICMP echo requests.
Test-NetConnection example.com -Port 443Test TCP connectivity to a port.
Resolve-DnsName example.comQuery DNS.
Get-DnsClientServerAddressShow configured DNS servers.
Get-NetTCPConnectionList TCP connections.
Get-NetTCPConnection -State ListenShow listening TCP sockets.
Get-NetUDPEndpointList UDP endpoints.
Get-NetAdapterStatisticsShow interface counters.
ipconfig /allRun classic Windows IP configuration output.
arp -aRun classic ARP table display.
route printRun classic routing table display.
nslookup example.comRun classic DNS lookup.
Get-NetFirewallProfileShow Windows Firewall profiles.
Get-NetFirewallRuleList firewall rules.
Get-NetFirewallRule -Enabled TrueList enabled rules.
New-NetFirewallRule -DisplayName 'Allow HTTP' -Direction Inbound -Protocol TCP -LocalPort 80 -Action AllowAllow inbound TCP port 80.
Disable-NetFirewallRule -DisplayName 'Rule Name'Disable a firewall rule.
Enable-NetFirewallRule -DisplayName 'Rule Name'Enable a firewall rule.
Remove-NetFirewallRule -DisplayName 'Rule Name'Delete a firewall rule. ⚠
Get-NetFirewallPortFilterInspect firewall port filters.
Get-LocalUserList local users.
Get-LocalUser administratorGet a local user.
New-LocalUser 'student' -NoPasswordCreate a local user without a password.
Set-LocalUser 'student' -Description 'Lab account'Modify a local user.
Disable-LocalUser studentDisable a local account.
Enable-LocalUser studentEnable a local account.
Remove-LocalUser studentDelete a local account. ⚠
Get-LocalGroupList local groups.
Get-LocalGroupMember AdministratorsList members of the Administrators group.
Add-LocalGroupMember Administrators studentAdd a local user to Administrators.
Remove-LocalGroupMember Administrators studentRemove a member from Administrators.
whoamiShow current user.
whoami /groupsShow current user's groups.
Import-Module ActiveDirectoryLoad the Active Directory module.
Get-ADUser -Filter *List AD users.
Get-ADUser username -Properties *Show all user properties.
Get-ADComputer -Filter *List AD computers.
Get-ADGroup -Filter *List AD groups.
Get-ADGroupMember 'Domain Admins'List group members.
New-ADUser -Name 'Test User' -SamAccountName tuser -Enabled $trueCreate an AD user.
Set-ADUser tuser -Department ITModify an AD user.
Disable-ADAccount tuserDisable an AD account.
Enable-ADAccount tuserEnable an AD account.
Unlock-ADAccount tuserUnlock an AD user account.
Add-ADGroupMember 'IT Staff' tuserAdd a user to an AD group.
Remove-ADGroupMember 'IT Staff' tuser -Confirm:$falseRemove a user from an AD group.
Get-ADDomainShow domain information.
Get-ADForestShow forest information.
Get-ChildItem HKLM:\SoftwareList registry keys.
Get-Item HKLM:\Software\MicrosoftGet a registry key.
Get-ItemProperty HKLM:\Software\MicrosoftRead registry values.
New-Item HKCU:\Software\MyAppCreate a registry key.
New-ItemProperty HKCU:\Software\MyApp -Name Enabled -Value 1 -PropertyType DWordCreate a registry value.
Set-ItemProperty HKCU:\Software\MyApp -Name Enabled -Value 0Modify a registry value.
Remove-ItemProperty HKCU:\Software\MyApp -Name EnabledDelete a registry value. ⚠
Remove-Item HKCU:\Software\MyApp -RecurseDelete a registry key tree. ⚠
Get-WinEvent -ListLog *List Windows event logs.
Get-WinEvent -LogName System -MaxEvents 20Show recent System events.
Get-WinEvent -LogName Application -MaxEvents 20Show recent Application events.
Get-WinEvent -FilterHashtable @{LogName='System'; Level=2}Show System errors.
Get-WinEvent -FilterHashtable @{LogName='System'; StartTime=(Get-Date).AddHours(-1)}Show System events from the last hour.
Get-EventLog -LogName System -Newest 20Legacy event log query.
Clear-EventLog -LogName ApplicationClear an event log. ⚠
Get-CimClassList CIM classes.
Get-CimInstance Win32_OperatingSystemQuery OS information.
Get-CimInstance Win32_ProcessQuery processes.
Get-CimInstance Win32_NetworkAdapterConfigurationQuery network adapter configuration.
Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine='notepad.exe'}Invoke a CIM method.
New-CimSession -ComputerName Server01Create a remote CIM session.
Get-CimInstance Win32_OperatingSystem -CimSession $sessionQuery through a CIM session.
Remove-CimSession $sessionClose a CIM session.
Enable-PSRemoting -ForceEnable PowerShell remoting on Windows.
Test-WSMan Server01Test WinRM connectivity.
Enter-PSSession Server01Open an interactive remote session.
Exit-PSSessionLeave an interactive remote session.
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Service }Run a command remotely.
Invoke-Command -ComputerName Server01,Server02 -ScriptBlock { hostname }Run across multiple computers.
$s = New-PSSession Server01Create a persistent remote session.
Invoke-Command -Session $s -ScriptBlock { Get-Process }Use a persistent session.
Remove-PSSession $sClose a persistent session.
Copy-Item file.txt C:\Temp -ToSession $sCopy a file into a remote session.
Get-ScheduledTaskList scheduled tasks.
Get-ScheduledTask -TaskName 'TaskName'Get one scheduled task.
Start-ScheduledTask -TaskName 'TaskName'Run a scheduled task now.
Stop-ScheduledTask -TaskName 'TaskName'Stop a running task.
Enable-ScheduledTask -TaskName 'TaskName'Enable a task.
Disable-ScheduledTask -TaskName 'TaskName'Disable a task.
Unregister-ScheduledTask -TaskName 'TaskName' -Confirm:$falseDelete a scheduled task. ⚠
$action = New-ScheduledTaskAction -Execute 'notepad.exe'Create a scheduled-task action.
$trigger = New-ScheduledTaskTrigger -Daily -At 9amCreate a daily trigger.
Register-ScheduledTask -TaskName 'Demo' -Action $action -Trigger $triggerRegister a scheduled task.
Get-DiskList physical disks.
Get-PhysicalDiskList physical disks through Storage Spaces.
Get-PartitionList partitions.
Get-VolumeList volumes.
Get-PSDrive -PSProvider FileSystemList filesystem drives.
Get-StoragePoolList storage pools.
Get-VirtualDiskList virtual disks.
Initialize-Disk -Number 1 -PartitionStyle GPTInitialize a disk. ⚠
New-Partition -DiskNumber 1 -UseMaximumSize -AssignDriveLetterCreate a partition.
Format-Volume -DriveLetter E -FileSystem NTFS -NewFileSystemLabel DataFormat a volume. ⚠
Resize-Partition -DriveLetter C -Size 200GBResize a partition when supported.
Get-PrinterList printers.
Get-PrinterDriverList printer drivers.
Get-PrinterPortList printer ports.
Add-PrinterPort -Name 'IP_10.0.0.50' -PrinterHostAddress 10.0.0.50Create a TCP/IP printer port.
Add-Printer -Name 'Office Printer' -DriverName 'Driver Name' -PortName 'IP_10.0.0.50'Add a printer.
Remove-Printer -Name 'Office Printer'Remove a printer. ⚠
Get-PrintJob -PrinterName 'Office Printer'List print jobs.
Remove-PrintJob -PrinterName 'Office Printer' -ID 3Delete a print job.
Get-PackageList installed packages known to PackageManagement.
Find-Package -Name 7zipSearch package sources.
Install-Package -Name PackageNameInstall a package through PackageManagement.
Uninstall-Package -Name PackageNameUninstall a package.
winget search vscodeSearch Windows Package Manager.
winget install Microsoft.VisualStudioCodeInstall a package with winget.
winget upgrade --allUpgrade all available winget packages.
winget listList installed packages visible to winget.
winget uninstall PackageNameUninstall with winget.
Get-ModuleList currently loaded modules.
Get-Module -ListAvailableList available modules.
Import-Module ActiveDirectoryImport a module.
Remove-Module ModuleNameUnload a module from the current session.
Find-Module PesterSearch PowerShell Gallery.
Install-Module Pester -Scope CurrentUserInstall a module from PowerShell Gallery.
Update-Module PesterUpdate an installed module.
Uninstall-Module PesterRemove a module.
Import-Csv users.csvRead CSV rows as objects.
$data | Export-Csv users.csv -NoTypeInformationWrite objects to CSV.
ConvertTo-Csv $data -NoTypeInformationConvert objects to CSV text.
Get-Content data.json -Raw | ConvertFrom-JsonParse JSON from a file.
$obj | ConvertTo-Json -Depth 5Convert an object to JSON.
$obj | ConvertTo-Json | Set-Content data.jsonWrite JSON to a file.
[xml]$xml = Get-Content file.xmlLoad XML into an XML document object.
$xml.SelectNodes('//item')Query XML nodes.
Invoke-WebRequest https://example.comMake a web request.
Invoke-WebRequest https://example.com/file.zip -OutFile file.zipDownload a file.
Invoke-RestMethod https://api.example.com/itemsCall a REST API and deserialize JSON.
Invoke-RestMethod -Method Post -Uri $uri -Body ($body | ConvertTo-Json) -ContentType 'application/json'POST JSON to a REST API.
$response.StatusCodeRead HTTP status code from Invoke-WebRequest.
$response.ContentRead raw response content.
Get-DateGet current date and time.
Get-Date -Format 'yyyy-MM-dd HH:mm:ss'Format date/time.
(Get-Date).AddDays(7)Add seven days.
(Get-Date).AddHours(-1)Subtract one hour.
New-TimeSpan -Start $start -End $endCalculate a time span.
[datetime]'2026-09-18'Convert text to a DateTime.
[timespan]::FromMinutes(5)Create a TimeSpan.
'abc123' -match '\d+'Regex match.
$Matches[0]Read the latest regex match.
'abc123' -replace '\d+','X'Regex replacement.
[regex]::Matches($text,'\b\w+\b')Return all regex matches.
[regex]::Escape($text)Escape regex metacharacters.
Select-String -Pattern '^ERROR' -Path *.logRegex search across files.
Get-ExecutionPolicyShow current script execution policy.
Get-ExecutionPolicy -ListShow execution policies by scope.
Set-ExecutionPolicy RemoteSigned -Scope CurrentUserSet current-user execution policy.
Get-CredentialPrompt for a PSCredential.
$cred.UserNameRead username from a PSCredential.
$cred.GetNetworkCredential().PasswordExtract plaintext password from a credential object; handle carefully.
ConvertTo-SecureString 'password' -AsPlainText -ForceCreate a SecureString from plaintext; avoid hardcoding secrets.
Get-AuthenticodeSignature .\script.ps1Inspect a script's code signature.
Set-AuthenticodeSignature .\script.ps1 $certSign a script using a certificate.
Start-Job { Get-Process }Start a background job.
Get-JobList background jobs.
Receive-Job -Id 1Receive job output.
Wait-Job -Id 1Wait for a job.
Stop-Job -Id 1Stop a job.
Remove-Job -Id 1Remove a job record.
1..10 | ForEach-Object -Parallel { $_ * 2 }Run pipeline work in parallel in PowerShell 7+.
Start-ThreadJob { Get-Service }Start a lightweight thread job if ThreadJob is available.
Start-Transcript -Path session.logRecord a PowerShell session transcript.
Stop-TranscriptStop transcript recording.
Write-Information 'Info message'Write to the information stream.
Write-Verbose 'Verbose message' -VerboseEmit verbose output.
Write-Debug 'Debug message' -DebugEmit debug output.
.\script.ps1Run a PowerShell script from the current directory.
powershell.exe -File script.ps1Run a script with Windows PowerShell.
pwsh -File script.ps1Run a script with PowerShell 7+.
powershell.exe -ExecutionPolicy Bypass -File script.ps1Run a script with a process-specific execution-policy override.
& 'C:\Path With Spaces\app.exe')Invoke an executable or script path.
. .\functions.ps1Dot-source a script into the current scope.
$PSScriptRootDirectory containing the running script.
$PSCommandPathFull path to the running script.
$a -eq $bEqual.
$a -ne $bNot equal.
$a -gt $bGreater than.
$a -ge $bGreater than or equal.
$a -lt $bLess than.
$a -le $bLess than or equal.
$text -like '*admin*'Wildcard comparison.
$text -notlike '*admin*'Negated wildcard comparison.
$text -match '^A'Regex comparison.
$text -notmatch '^A'Negated regex comparison.
$items -contains 'x'Collection contains a value.
'x' -in $itemsValue exists in collection.
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 Name,CPU,IdTop 10 processes by CPU.
Get-Process | Sort-Object WS -Descending | Select-Object -First 10 Name,@{N='MB';E={[math]::Round($_.WS/1MB,1)}}Top 10 processes by working-set memory.
Get-Service | Where-Object Status -eq 'Stopped' | Sort-Object NameList stopped services.
Get-ChildItem C:\ -File -Recurse -ErrorAction SilentlyContinue | Sort-Object Length -Descending | Select-Object -First 20 FullName,LengthFind large files. Can take a while.
Get-ChildItem -Recurse -File | Measure-Object | Select-Object CountCount files recursively.
Get-WinEvent -FilterHashtable @{LogName='System';Level=2;StartTime=(Get-Date).AddHours(-24)}Show System errors from the last 24 hours.
Get-NetTCPConnection -State Listen | Sort-Object LocalPortShow listening TCP ports.
Get-LocalGroupMember AdministratorsQuickly list local admins.
Get-CimInstance Win32_OperatingSystem | Select-Object Caption,Version,LastBootUpTimeShow OS version and last boot time.
Get-Disk | Select-Object Number,FriendlyName,Size,PartitionStyle,OperationalStatusSummarize disks.
Get-Volume | Sort-Object DriveLetter | Format-Table DriveLetter,FileSystemLabel,FileSystem,SizeRemaining,SizeSummarize volumes.
Get-ChildItem *.log | Select-String 'error|failed' -CaseSensitive:$falseSearch log files for common failure terms.
1..20 | ForEach-Object { Test-Connection 192.168.1.$_ -Count 1 -Quiet }Basic ping sweep result list.
Format-Table | Export-CsvDo not format objects before exporting; formatting converts objects into display metadata.
Where-Object {$_.Property = 'x'}Use -eq for comparison; = assigns a value.
Write-Host $obj | Export-Csv file.csvWrite-Host does not emit normal pipeline objects for export.
Remove-Item -Recurse -ForceDouble-check target paths before destructive recursive deletion.
$array += $itemRepeated += on very large arrays can be inefficient; prefer List[T] or pipeline collection.
Get-WmiObjectPrefer Get-CimInstance for modern PowerShell automation.