Commands that also list Linux and macOS work in PowerShell 7 on those systems. Tasks marked (PowerShell 7) don't work in Windows PowerShell 5.1. Tasks marked (as admin) need PowerShell opened with Run as administrator. The Active Directory commands need the Active Directory module. Names, paths and addresses are examples, so swap in your own.
Getting started and help #
-
Show the PowerShell versionLinux, macOS, Windows
$PSVersionTable.PSVersion -
Install PowerShell 7Windows
winget install Microsoft.PowerShell -
Start PowerShell 7 from another shellLinux, macOS, Windows
pwsh -
Get help for a commandLinux, macOS, Windows
Get-Help Get-Process -Detailed -
Show examples for a commandLinux, macOS, Windows
Get-Help Get-Process -Examples -
Open a command's help page in your browserLinux, macOS, Windows
Get-Help Get-Process -Online -
Download the latest help files (PowerShell 7)Linux, macOS, Windows
Update-Help -Scope CurrentUser -
Find commands by nameLinux, macOS, Windows
Get-Command *service* -
Find commands that work with somethingLinux, macOS, Windows
Get-Command -Noun Process -
Show the properties and methods a command's output hasLinux, macOS, Windows
Get-Process | Get-Member -
Find out what an alias stands forLinux, macOS, Windows
Get-Alias ls -
Show the commands you've typed in this sessionLinux, macOS, Windows
Get-History -
Search commands from earlier sessionsLinux, macOS, Windows
Get-Content (Get-PSReadLineOption).HistorySavePath | Select-String "docker" -
Clear the screenLinux, macOS, Windows
Clear-Host -
Create your profile script if it doesn't existLinux, macOS, Windows
if (!(Test-Path $PROFILE)) { New-Item -Path $PROFILE -ItemType File -Force } -
Edit your profile scriptWindows
notepad $PROFILE -
Reload your profile scriptLinux, macOS, Windows
. $PROFILE
Files and folders #
-
Show the current folderLinux, macOS, Windows
Get-Location -
Go to a folderLinux, macOS, Windows
Set-Location ~/Projects -
List files and foldersLinux, macOS, Windows
Get-ChildItem -
List files, including hidden onesLinux, macOS, Windows
Get-ChildItem -Force -
List only foldersLinux, macOS, Windows
Get-ChildItem -Directory -
Find files by name in all subfoldersLinux, macOS, Windows
Get-ChildItem -Recurse -Filter *.log -
List files by size, largest firstLinux, macOS, Windows
Get-ChildItem -File | Sort-Object Length -Descending -
Find the 10 largest files in all subfoldersLinux, macOS, Windows
Get-ChildItem -Recurse -File | Sort-Object Length -Descending | Select-Object -First 10 FullName, Length -
Find files changed in the last 7 daysLinux, macOS, Windows
Get-ChildItem -Recurse -File | Where-Object LastWriteTime -gt (Get-Date).AddDays(-7) -
Show a folder's total size in GBLinux, macOS, Windows
(Get-ChildItem -Recurse -File | Measure-Object Length -Sum).Sum / 1GB -
Create a folder and any missing parent foldersLinux, macOS, Windows
New-Item -ItemType Directory -Path projects/site/assets -Force -
Create an empty fileLinux, macOS, Windows
New-Item -ItemType File -Path notes.txt -
Check whether a file or folder existsLinux, macOS, Windows
Test-Path notes.txt -
Show all of a file's propertiesLinux, macOS, Windows
Get-Item notes.txt | Format-List * -
Copy a fileLinux, macOS, Windows
Copy-Item report.docx backup/ -
Copy a folder and everything in itLinux, macOS, Windows
Copy-Item source -Destination backup -Recurse -
Move a file to another folderLinux, macOS, Windows
Move-Item report.docx archive/ -
Rename a fileLinux, macOS, Windows
Rename-Item old-name.txt new-name.txt -
Change the extension of every .txt fileLinux, macOS, Windows
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '\.txt$', '.bak' } -
Delete a fileLinux, macOS, Windows
Remove-Item file.txt -
Preview what a delete would removeLinux, macOS, Windows
Remove-Item *.tmp -WhatIf -
Delete matching files in all subfoldersLinux, macOS, Windows
Get-ChildItem -Recurse -Filter *.tmp | Remove-ItemWarning: Deletes without asking and skips the Recycle Bin.
-
Delete a folder and everything in itLinux, macOS, Windows
Remove-Item old-folder -Recurse -ForceWarning: Deletes without asking, skips the Recycle Bin and can't be undone.
-
Show a file's SHA-256 hashLinux, macOS, Windows
Get-FileHash setup.exe -
Compare the files in two foldersLinux, macOS, Windows
Compare-Object (Get-ChildItem folder1) (Get-ChildItem folder2) -Property Name -
Zip a folderLinux, macOS, Windows
Compress-Archive -Path site/* -DestinationPath site.zip -
Unzip a fileLinux, macOS, Windows
Expand-Archive site.zip -DestinationPath site -
Create a symbolic linkLinux, macOS, Windows
New-Item -ItemType SymbolicLink -Path link.txt -Target target.txt -
Open the current folder in File ExplorerWindows
Invoke-Item .
Reading and searching text #
-
Show a file's contentsLinux, macOS, Windows
Get-Content notes.txt -
Show the first 10 lines of a fileLinux, macOS, Windows
Get-Content app.log -TotalCount 10 -
Show the last 20 lines of a fileLinux, macOS, Windows
Get-Content app.log -Tail 20 -
Follow a log file as it growsLinux, macOS, Windows
Get-Content app.log -Wait -Tail 20 -
Search for text in a fileLinux, macOS, Windows
Select-String -Path app.log -Pattern "error" -
Search for text in all files in subfoldersLinux, macOS, Windows
Get-ChildItem -Recurse -Filter *.log | Select-String "error" -
Search for text, matching caseLinux, macOS, Windows
Select-String -Path app.log -Pattern "Error" -CaseSensitive -
Show lines that don't contain some textLinux, macOS, Windows
Select-String -Path app.log -Pattern "DEBUG" -NotMatch -
Show 2 lines either side of each matchLinux, macOS, Windows
Select-String -Path app.log -Pattern "error" -Context 2,2 -
Count the matches in a fileLinux, macOS, Windows
(Select-String -Path app.log -Pattern "error").Count -
Count the lines, words and characters in a fileLinux, macOS, Windows
Get-Content notes.txt | Measure-Object -Line -Word -Character -
Replace a file's contents with some textLinux, macOS, Windows
"Hello" | Set-Content notes.txt -
Add a line to the end of a fileLinux, macOS, Windows
Add-Content log.txt "Backup done" -
Save a command's output to a fileLinux, macOS, Windows
Get-Process | Out-File processes.txt -
Replace text in a fileLinux, macOS, Windows
(Get-Content config.txt) -replace 'old', 'new' | Set-Content config.txtWarning: Changes the file straight away, with no backup.
-
Show a file's unique lines, sortedLinux, macOS, Windows
Get-Content names.txt | Sort-Object -Unique -
Compare two filesLinux, macOS, Windows
Compare-Object (Get-Content file1.txt) (Get-Content file2.txt) -
Copy a command's output to the clipboardWindows
Get-Process | Set-Clipboard -
Show what's on the clipboardWindows
Get-Clipboard
Pipeline, filtering and formatting #
-
Keep only items that match a conditionLinux, macOS, Windows
Get-Process | Where-Object CPU -gt 100 -
Keep only items that match several conditionsLinux, macOS, Windows
Get-Process | Where-Object { $_.CPU -gt 10 -and $_.WorkingSet64 -gt 200MB } -
Choose which properties to showLinux, macOS, Windows
Get-Process | Select-Object Name, Id, CPU -
Show just the values of one propertyLinux, macOS, Windows
(Get-Process).Name -
Show the unique values of a propertyLinux, macOS, Windows
Get-Process | Select-Object -ExpandProperty Name -Unique -
Sort and show the top 5Linux, macOS, Windows
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 -
Group items and count each groupLinux, macOS, Windows
Get-Process | Group-Object Name | Sort-Object Count -Descending -
Count itemsLinux, macOS, Windows
(Get-Process).Count -
Show the total, average and largest of a propertyLinux, macOS, Windows
Get-ChildItem -File | Measure-Object Length -Sum -Average -Maximum -
Run something for each itemLinux, macOS, Windows
Get-ChildItem *.log | ForEach-Object { $_.Name.ToUpper() } -
Run something for each item in parallel (PowerShell 7)Linux, macOS, Windows
1..5 | ForEach-Object -Parallel { Start-Sleep 1; $_ } -ThrottleLimit 5 -
Add a calculated columnLinux, macOS, Windows
Get-ChildItem -File | Select-Object Name, @{Name='SizeMB'; Expression={[math]::Round($_.Length / 1MB, 2)}} -
Show output as a tableLinux, macOS, Windows
Get-Process | Format-Table Name, Id, CPU -AutoSize -
Show every property as a listLinux, macOS, Windows
Get-Process -Id $PID | Format-List * -
Show output and save it to a file at the same timeLinux, macOS, Windows
Get-Process | Tee-Object -FilePath processes.txt -
Show output in a sortable, filterable windowWindows
Get-Process | Out-GridView
Variables, objects and scripting #
-
Set a variableLinux, macOS, Windows
$name = "Gerard" -
List all environment variablesLinux, macOS, Windows
Get-ChildItem Env: -
Show an environment variableLinux, macOS, Windows
$env:PATH -
Set an environment variable for this sessionLinux, macOS, Windows
$env:APP_ENV = "dev" -
Set an environment variable permanently for your accountWindows
[Environment]::SetEnvironmentVariable("APP_ENV", "dev", "User") -
Ask the user to type somethingLinux, macOS, Windows
$name = Read-Host "Enter your name" -
Ask for a password without showing itLinux, macOS, Windows
$secret = Read-Host "Password" -AsSecureString -
Ask for a username and passwordLinux, macOS, Windows
$cred = Get-Credential -
Create a list (array)Linux, macOS, Windows
$servers = @("web01", "web02", "db01") -
Create a hashtableLinux, macOS, Windows
$config = @{ Name = "web"; Port = 8080 } -
Create a custom objectLinux, macOS, Windows
[PSCustomObject]@{ Name = "web01"; Status = "Up" } -
Loop through a listLinux, macOS, Windows
foreach ($s in $servers) { Test-Connection $s -Count 1 } -
Loop through a range of numbersLinux, macOS, Windows
1..5 | ForEach-Object { "Server $_" } -
Do something only if a file existsLinux, macOS, Windows
if (Test-Path config.json) { "Found" } else { "Missing" } -
Catch an errorLinux, macOS, Windows
try { Get-Item missing.txt -ErrorAction Stop } catch { "Error: $_" } -
Check whether the last command workedLinux, macOS, Windows
$? -
Show the exit code of the last programLinux, macOS, Windows
$LASTEXITCODE -
Show the date and timeLinux, macOS, Windows
Get-Date -
Show the date in a custom formatLinux, macOS, Windows
Get-Date -Format "yyyy-MM-dd HH:mm" -
Get the date 30 days agoLinux, macOS, Windows
(Get-Date).AddDays(-30) -
Time how long a command takesLinux, macOS, Windows
Measure-Command { Get-ChildItem -Recurse } -
Wait 10 secondsLinux, macOS, Windows
Start-Sleep -Seconds 10 -
Print a message in colourLinux, macOS, Windows
Write-Host "Done" -ForegroundColor Green -
Run a script in the current folderLinux, macOS, Windows
./backup.ps1 -
Run a script with parametersLinux, macOS, Windows
./backup.ps1 -Path ~/Documents -
Record everything in this session to a fileLinux, macOS, Windows
Start-Transcript -Path session.log -
Stop recording the sessionLinux, macOS, Windows
Stop-Transcript -
Generate a GUIDLinux, macOS, Windows
New-Guid -
Generate a random 16-character passwordLinux, macOS, Windows
-join ((48..57) + (65..90) + (97..122) | Get-Random -Count 16 | ForEach-Object { [char]$_ })
CSV, JSON and other formats #
-
Read a CSV fileLinux, macOS, Windows
Import-Csv users.csv -
Save output as a CSV fileLinux, macOS, Windows
Get-Process | Select-Object Name, Id, CPU | Export-Csv processes.csv -NoTypeInformation -
Read a JSON fileLinux, macOS, Windows
Get-Content config.json -Raw | ConvertFrom-Json -
Convert output to JSONLinux, macOS, Windows
Get-Process | Select-Object Name, Id | ConvertTo-Json -
Save an object as a JSON fileLinux, macOS, Windows
$config | ConvertTo-Json -Depth 5 | Set-Content config.json -
Read an XML fileLinux, macOS, Windows
[xml]$xml = Get-Content config.xml -
Save output as an HTML reportLinux, macOS, Windows
Get-Process | Select-Object Name, CPU | ConvertTo-Html | Out-File report.html -
Save objects to a file exactly as they areLinux, macOS, Windows
Get-Process | Export-Clixml processes.xml -
Load objects saved with Export-ClixmlLinux, macOS, Windows
Import-Clixml processes.xml
Processes and jobs #
-
List running processesLinux, macOS, Windows
Get-Process -
Find a process by nameLinux, macOS, Windows
Get-Process -Name chrome -
Show the 10 processes using the most memoryLinux, macOS, Windows
Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 10 Name, Id, @{Name='MemoryMB'; Expression={[math]::Round($_.WorkingSet64 / 1MB)}} -
Show the 10 processes using the most CPULinux, macOS, Windows
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 -
Show where a running program is installedLinux, macOS, Windows
Get-Process -Name code | Select-Object Name, Path -
Stop a process by nameLinux, macOS, Windows
Stop-Process -Name notepad -
Stop a process by its IDLinux, macOS, Windows
Stop-Process -Id 1234 -
Force a process to stopLinux, macOS, Windows
Stop-Process -Name chrome -ForceWarning: The program can't clean up, so unsaved work may be lost.
-
Wait for a process to finishLinux, macOS, Windows
Wait-Process -Name setup -
Start a programWindows
Start-Process notepad -
Start a program and wait for it to finishWindows
Start-Process setup.exe -Wait -
Open PowerShell as administratorWindows
Start-Process pwsh -Verb RunAs -
Run a command in the backgroundLinux, macOS, Windows
Start-Job { Get-ChildItem -Recurse ~ } -
Run a command in the background with & (PowerShell 7)Linux, macOS, Windows
Get-ChildItem -Recurse ~ & -
List background jobsLinux, macOS, Windows
Get-Job -
Wait for a background job to finishLinux, macOS, Windows
Wait-Job -Id 1 -
Get a background job's outputLinux, macOS, Windows
Receive-Job -Id 1 -Keep -
Remove finished background jobsLinux, macOS, Windows
Get-Job -State Completed | Remove-Job
Services #
-
List servicesWindows
Get-Service -
List running servicesWindows
Get-Service | Where-Object Status -eq Running -
Show a service's statusWindows
Get-Service -Name spooler -
Find services by display nameWindows
Get-Service -DisplayName *update* -
Show the services that depend on a serviceWindows
Get-Service spooler -DependentServices -
Show a service's account and program pathWindows
Get-CimInstance Win32_Service -Filter "Name='spooler'" | Select-Object Name, StartName, PathName -
Start a service (as admin)Windows
Start-Service spooler -
Stop a service (as admin)Windows
Stop-Service spooler -
Restart a service (as admin)Windows
Restart-Service spooler -
Make a service start automatically (as admin)Windows
Set-Service spooler -StartupType Automatic -
Disable a service (as admin)Windows
Set-Service spooler -StartupType Disabled
System information #
-
Show the computer nameLinux, macOS, Windows
[System.Net.Dns]::GetHostName() -
Show the current userLinux, macOS, Windows
[Environment]::UserName -
Show how long the computer has been running (PowerShell 7)Linux, macOS, Windows
Get-Uptime -
Show the time zoneLinux, macOS, Windows
Get-TimeZone -
Change the time zone (as admin)Windows
Set-TimeZone -Id "GMT Standard Time" -
Show a full system summaryWindows
Get-ComputerInfo -
Show the Windows version and buildWindows
Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, BuildNumber -
Show when the computer last startedWindows
(Get-CimInstance Win32_OperatingSystem).LastBootUpTime -
Show the serial numberWindows
(Get-CimInstance Win32_BIOS).SerialNumber -
Show the CPU and core countWindows
Get-CimInstance Win32_Processor | Select-Object Name, NumberOfCores, NumberOfLogicalProcessors -
Show the installed memory in GBWindows
(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB -
List installed updates, newest firstWindows
Get-HotFix | Sort-Object InstalledOn -Descending -
List installed programsWindows
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion | Sort-Object DisplayName -
List drivers and their versionsWindows
Get-CimInstance Win32_PnPSignedDriver | Select-Object DeviceName, DriverVersion -
List devices that have a problemWindows
Get-PnpDevice -Status ERROR
Network #
-
Check you can reach a hostLinux, macOS, Windows
Test-Connection 8.8.8.8 -Count 4 -
Test whether a TCP port is open (PowerShell 7)Linux, macOS, Windows
Test-Connection server01 -TcpPort 443 -
Show your public IP addressLinux, macOS, Windows
Invoke-RestMethod https://api.ipify.org -
Show your IP addressesWindows
Get-NetIPAddress -AddressFamily IPv4 -
Show each adapter's IP, gateway and DNS settingsWindows
Get-NetIPConfiguration -
List network adaptersWindows
Get-NetAdapter -
Test a port and show connection detailsWindows
Test-NetConnection server01 -Port 443 -
Trace the route to a hostWindows
Test-NetConnection google.com -TraceRoute -
Look up a domain's IP addressWindows
Resolve-DnsName example.com -
Look up a domain's mail (MX) recordsWindows
Resolve-DnsName example.com -Type MX -
Look up a domain using a specific DNS serverWindows
Resolve-DnsName example.com -Server 1.1.1.1 -
Show the DNS cacheWindows
Get-DnsClientCache -
Clear the DNS cache (as admin)Windows
Clear-DnsClientCache -
Show your DNS serversWindows
Get-DnsClientServerAddress -AddressFamily IPv4 -
Set an adapter's DNS servers (as admin)Windows
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses 1.1.1.1, 8.8.8.8 -
Set a static IP address (as admin)Windows
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.1.50 -PrefixLength 24 -DefaultGateway 192.168.1.1 -
Switch an adapter to DHCP (as admin)Windows
Set-NetIPInterface -InterfaceAlias "Ethernet" -Dhcp Enabled -
List listening portsWindows
Get-NetTCPConnection -State Listen -
List open connectionsWindows
Get-NetTCPConnection -State Established -
Find which program is using a portWindows
Get-NetTCPConnection -LocalPort 8080 | Select-Object LocalPort, OwningProcess, @{Name='Process'; Expression={(Get-Process -Id $_.OwningProcess).Name}} -
Show the routing tableWindows
Get-NetRoute -
Show the ARP tableWindows
Get-NetNeighbor -
Restart a network adapter (as admin)Windows
Restart-NetAdapter -Name "Ethernet" -
Disable a network adapter (as admin)Windows
Disable-NetAdapter -Name "Wi-Fi" -Confirm:$false -
Enable a network adapter (as admin)Windows
Enable-NetAdapter -Name "Wi-Fi" -
Show whether each network is public or privateWindows
Get-NetConnectionProfile -
Set a network to private (as admin)Windows
Set-NetConnectionProfile -InterfaceAlias "Ethernet" -NetworkCategory Private
Web requests and APIs #
-
Download a fileLinux, macOS, Windows
Invoke-WebRequest https://example.com/file.zip -OutFile file.zip -
Check a website's status codeLinux, macOS, Windows
(Invoke-WebRequest https://example.com).StatusCode -
Show a website's response headersLinux, macOS, Windows
(Invoke-WebRequest https://example.com -Method Head).Headers -
Call a REST APILinux, macOS, Windows
Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell -
Send JSON to an APILinux, macOS, Windows
Invoke-RestMethod -Uri https://api.example.com/items -Method Post -Body (@{ name = "test" } | ConvertTo-Json) -ContentType "application/json" -
Call an API with a tokenLinux, macOS, Windows
Invoke-RestMethod https://api.example.com/me -Headers @{ Authorization = "Bearer $token" } -
Call a site with a self-signed certificate (PowerShell 7)Linux, macOS, Windows
Invoke-RestMethod https://192.168.1.50:8006/api2/json/version -SkipCertificateCheckWarning: Turns off certificate checks. Only use it on your own servers.
Local users and groups #
-
List local usersWindows
Get-LocalUser -
Show a local user's detailsWindows
Get-LocalUser alice | Format-List * -
Create a local user (asks for the password) (as admin)Windows
New-LocalUser -Name alice -Password (Read-Host -AsSecureString "Password") -
Change a local user's password (as admin)Windows
Set-LocalUser -Name alice -Password (Read-Host -AsSecureString "Password") -
Disable a local user (as admin)Windows
Disable-LocalUser alice -
Enable a local user (as admin)Windows
Enable-LocalUser alice -
Delete a local user (as admin)Windows
Remove-LocalUser aliceWarning: Deletes the account and can't be undone.
-
List local groupsWindows
Get-LocalGroup -
List the members of the Administrators groupWindows
Get-LocalGroupMember Administrators -
Add a user to the Administrators group (as admin)Windows
Add-LocalGroupMember -Group Administrators -Member alice -
Remove a user from the Administrators group (as admin)Windows
Remove-LocalGroupMember -Group Administrators -Member alice
Active Directory #
-
Install the Active Directory module on Windows 11 (as admin)Windows
Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0 -
Load the Active Directory moduleWindows
Import-Module ActiveDirectory -
Show a user's detailsWindows
Get-ADUser alice -Properties * -
Find users by nameWindows
Get-ADUser -Filter "Name -like '*smith*'" -
List locked-out usersWindows
Search-ADAccount -LockedOut -
Unlock a userWindows
Unlock-ADAccount alice -
List disabled usersWindows
Search-ADAccount -AccountDisabled -UsersOnly -
List users who haven't signed in for 90 daysWindows
Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 -UsersOnly -
List users whose password has expiredWindows
Search-ADAccount -PasswordExpired -
Reset a user's passwordWindows
Set-ADAccountPassword alice -Reset -NewPassword (Read-Host -AsSecureString "New password") -
Make a user change their password at next sign-inWindows
Set-ADUser alice -ChangePasswordAtLogon $true -
Create a userWindows
New-ADUser -Name "Alice Smith" -SamAccountName alice -UserPrincipalName [email protected] -AccountPassword (Read-Host -AsSecureString "Password") -Enabled $true -
Disable a userWindows
Disable-ADAccount alice -
Delete a userWindows
Remove-ADUser aliceWarning: Deletes the account and can't be undone unless the AD Recycle Bin is turned on.
-
List the groups a user is inWindows
Get-ADPrincipalGroupMembership alice | Select-Object Name -
List a group's membersWindows
Get-ADGroupMember "IT Staff" -
Add a user to a groupWindows
Add-ADGroupMember "IT Staff" -Members alice -
Remove a user from a groupWindows
Remove-ADGroupMember "IT Staff" -Members alice -Confirm:$false -
Show a computer's detailsWindows
Get-ADComputer server01 -Properties * -
List the computers in an OUWindows
Get-ADComputer -Filter * -SearchBase "OU=Servers,DC=corp,DC=example,DC=com" -
List domain controllersWindows
Get-ADDomainController -Filter * -
Show domain detailsWindows
Get-ADDomain
Remoting #
-
Turn on PowerShell remoting (as admin)Windows
Enable-PSRemoting -Force -
Check remoting works on another computerWindows
Test-WSMan server01 -
Trust a computer that isn't in your domain (as admin)Windows
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "192.168.1.50" -Concatenate -Force -
Open a session on another computerWindows
Enter-PSSession -ComputerName server01 -
Open a session as another userWindows
Enter-PSSession -ComputerName server01 -Credential (Get-Credential) -
Open a session over SSH (PowerShell 7)Linux, macOS, Windows
Enter-PSSession -HostName user@server01 -
Leave a remote sessionLinux, macOS, Windows
Exit-PSSession -
Run a command on another computerWindows
Invoke-Command -ComputerName server01 -ScriptBlock { Get-Service spooler } -
Run a command on several computersWindows
Invoke-Command -ComputerName web01, web02, db01 -ScriptBlock { (Get-CimInstance Win32_OperatingSystem).LastBootUpTime } -
Run a local script on another computerWindows
Invoke-Command -ComputerName server01 -FilePath ./check.ps1 -
Create a session you can reuseWindows
$s = New-PSSession -ComputerName server01 -
Copy a file to a remote sessionWindows
Copy-Item ./setup.msi -Destination C:\Temp\ -ToSession $s -
Copy a file from a remote sessionWindows
Copy-Item C:\Logs\app.log -Destination . -FromSession $s -
Close all remote sessionsLinux, macOS, Windows
Get-PSSession | Remove-PSSession
Execution policy and security #
-
Show the execution policyWindows
Get-ExecutionPolicy -
Show the execution policy for each scopeWindows
Get-ExecutionPolicy -List -
Allow local scripts and signed downloaded ones for your accountWindows
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -
Allow all scripts in this window onlyWindows
Set-ExecutionPolicy Bypass -Scope ProcessWarning: Lets any script run in this window, including ones you didn't write.
-
Run one script without changing the policyWindows
pwsh -ExecutionPolicy Bypass -File ./script.ps1 -
Unblock a script you downloadedWindows
Unblock-File ./script.ps1 -
Check a script's digital signatureWindows
Get-AuthenticodeSignature ./script.ps1 -
Show Microsoft Defender statusWindows
Get-MpComputerStatus -
Run a Defender quick scanWindows
Start-MpScan -ScanType QuickScan -
Update Defender's virus definitionsWindows
Update-MpSignature -
Show threats Defender has foundWindows
Get-MpThreatDetection -
Show BitLocker status for each drive (as admin)Windows
Get-BitLockerVolume
Modules #
-
List loaded modulesLinux, macOS, Windows
Get-Module -
List installed modulesLinux, macOS, Windows
Get-Module -ListAvailable -
Search the PowerShell Gallery for modulesLinux, macOS, Windows
Find-Module *azure* -
Install a module for your accountLinux, macOS, Windows
Install-Module Az -Scope CurrentUser -
Install a module with PSResourceGet (PowerShell 7)Linux, macOS, Windows
Install-PSResource Az -Scope CurrentUser -
Update a moduleLinux, macOS, Windows
Update-Module Az -
Load a moduleLinux, macOS, Windows
Import-Module Az.Accounts -
List the commands in a moduleLinux, macOS, Windows
Get-Command -Module Microsoft.PowerShell.Archive -
Uninstall a moduleLinux, macOS, Windows
Uninstall-Module Az
Event logs #
-
List event logs that have entriesWindows
Get-WinEvent -ListLog * | Where-Object RecordCount -gt 0 -
Show the 20 latest System eventsWindows
Get-WinEvent -LogName System -MaxEvents 20 -
Show System errors from the last 24 hoursWindows
Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 2; StartTime = (Get-Date).AddDays(-1) } -
Show recent failed sign-ins (as admin)Windows
Get-WinEvent -FilterHashtable @{ LogName = 'Security'; Id = 4625 } -MaxEvents 20 -
Show recent startups and shutdownsWindows
Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 6005, 6006 } -MaxEvents 10 -
Show unexpected shutdowns and power lossesWindows
Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 41 } -
Save events to a CSV fileWindows
Get-WinEvent -LogName Application -MaxEvents 500 | Export-Csv app-events.csv -NoTypeInformation -
Clear an event log (as admin)Windows
[System.Diagnostics.Eventing.Reader.EventLogSession]::GlobalSession.ClearLog("Application")Warning: Deletes the log's entries and can't be undone.
Registry #
-
List the keys under a registry keyWindows
Get-ChildItem HKCU:\Software -
Show the programs that start when you sign inWindows
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -
Show one registry valueWindows
Get-ItemPropertyValue "HKCU:\Control Panel\Desktop" -Name WallPaper -
Check whether a registry key existsWindows
Test-Path "HKCU:\Software\MyApp" -
Create a registry keyWindows
New-Item -Path "HKCU:\Software\MyApp" -
Set a registry valueWindows
Set-ItemProperty -Path "HKCU:\Software\MyApp" -Name Mode -Value dev -
Create a number (DWORD) registry valueWindows
New-ItemProperty -Path "HKCU:\Software\MyApp" -Name Port -Value 8080 -PropertyType DWord -
Delete a registry valueWindows
Remove-ItemProperty -Path "HKCU:\Software\MyApp" -Name ModeWarning: Deletes the value without a backup.
-
Delete a registry key and everything in itWindows
Remove-Item -Path "HKCU:\Software\MyApp" -RecurseWarning: Deletes the key and all its values without a backup.
Disks and storage #
-
Show drives and their free spaceLinux, macOS, Windows
Get-PSDrive -PSProvider FileSystem -
List volumesWindows
Get-Volume -
List disksWindows
Get-Disk -
List partitionsWindows
Get-Partition -
Show each disk's type and healthWindows
Get-PhysicalDisk | Select-Object FriendlyName, MediaType, HealthStatus, Size -
Show disk temperature, wear and errors (as admin)Windows
Get-PhysicalDisk | Get-StorageReliabilityCounter | Select-Object DeviceId, Temperature, Wear, ReadErrorsTotal -
Set up a new disk with one NTFS partition (as admin)Windows
Initialize-Disk -Number 1 -PartitionStyle GPT; New-Partition -DiskNumber 1 -UseMaximumSize -AssignDriveLetter | Format-Volume -FileSystem NTFS -NewFileSystemLabel BackupWarning: Check the disk number with Get-Disk first.
-
Format a volume (as admin)Windows
Format-Volume -DriveLetter E -FileSystem NTFS -NewFileSystemLabel BackupWarning: Erases everything on the volume.
-
Wipe a disk (as admin)Windows
Clear-Disk -Number 1 -RemoveDataWarning: Erases every partition on the disk. Check the disk number with Get-Disk first.
-
Change a volume's name (as admin)Windows
Set-Volume -DriveLetter E -NewFileSystemLabel Backup -
Change a drive letter (as admin)Windows
Set-Partition -DriveLetter E -NewDriveLetter F -
Check a volume for errors (as admin)Windows
Repair-Volume -DriveLetter C -Scan -
Fix errors on a volume (as admin)Windows
Repair-Volume -DriveLetter C -OfflineScanAndFix -
Optimise a drive (as admin)Windows
Optimize-Volume -DriveLetter C -
Mount an ISO fileWindows
Mount-DiskImage -ImagePath C:\ISOs\windows.iso -
Unmount an ISO fileWindows
Dismount-DiskImage -ImagePath C:\ISOs\windows.iso
Firewall #
-
Show whether the firewall is on for each profileWindows
Get-NetFirewallProfile | Select-Object Name, Enabled -
Turn the firewall on (as admin)Windows
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True -
Turn the firewall off (as admin)Windows
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled FalseWarning: Leaves the computer unprotected. Turn it back on when you're done.
-
List enabled rules that allow incoming trafficWindows
Get-NetFirewallRule -Direction Inbound -Enabled True -Action Allow -
Allow incoming traffic on a port (as admin)Windows
New-NetFirewallRule -DisplayName "Allow 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow -
Allow incoming ping (as admin)Windows
New-NetFirewallRule -DisplayName "Allow ping" -Direction Inbound -Protocol ICMPv4 -IcmpType 8 -Action Allow -
Block a program from the internet (as admin)Windows
New-NetFirewallRule -DisplayName "Block app" -Direction Outbound -Program "C:\Apps\app.exe" -Action Block -
Show the ports a firewall rule coversWindows
Get-NetFirewallRule -DisplayName "Allow 8080" | Get-NetFirewallPortFilter -
Disable a firewall rule (as admin)Windows
Disable-NetFirewallRule -DisplayName "Allow 8080" -
Delete a firewall rule (as admin)Windows
Remove-NetFirewallRule -DisplayName "Allow 8080"
Scheduled tasks #
-
List scheduled tasksWindows
Get-ScheduledTask -
List scheduled tasks that aren't Microsoft'sWindows
Get-ScheduledTask | Where-Object { $_.TaskPath -notlike '\Microsoft\*' } -
Show when a task last ran and its resultWindows
Get-ScheduledTaskInfo -TaskName "Backup" -
Run a PowerShell script every day at 2amWindows
$action = New-ScheduledTaskAction -Execute "pwsh.exe" -Argument "-File C:\Scripts\backup.ps1"; $trigger = New-ScheduledTaskTrigger -Daily -At 2am; Register-ScheduledTask -TaskName "Backup" -Action $action -Trigger $trigger -
Run a scheduled task nowWindows
Start-ScheduledTask -TaskName "Backup" -
Disable a scheduled taskWindows
Disable-ScheduledTask -TaskName "Backup" -
Delete a scheduled taskWindows
Unregister-ScheduledTask -TaskName "Backup" -Confirm:$false
Restart and shut down #
-
Restart the computerWindows
Restart-Computer -
Force the computer to restartWindows
Restart-Computer -ForceWarning: Closes apps without saving.
-
Shut down the computerWindows
Stop-Computer -
Restart another computerWindows
Restart-Computer -ComputerName server01 -Force -
Restart another computer and wait until it's backWindows
Restart-Computer -ComputerName server01 -Wait -For PowerShell -Timeout 300 -
Rename the computer and restart (as admin)Windows
Rename-Computer -NewName web01 -Restart -
Join a domain and restart, in Windows PowerShell 5.1 (as admin)Windows
Add-Computer -DomainName corp.example.com -Credential (Get-Credential) -Restart