PowerShell cheat sheet

Searchable list of essential PowerShell cmdlets for files, processes, services, the pipeline and remoting, for PowerShell 7 and 5.1.

Runs in your browser ยท nothing is sentNew

44 commands

Get-Help <cmdlet> -FullShow the full help page for a cmdlet, including parameters and examples.

Without -Full you get a short summary. Add -Online to open the up-to-date web page instead, or -Examples for just the example section.

Example

Get-Help Get-ChildItem -Examples

Options

-OnlineOpen the latest documentation in your browser.
-ExamplesShow only usage examples.
-Parameter <name>Show help for one parameter.
Get-Command *process*Find cmdlets, functions and aliases by (partial) name.

Wildcards work on both sides. Use -Noun or -Verb to search by one part of a Verb-Noun name.

Example

Get-Command -Verb Get -Noun Service

Options

-Verb <verb>Only commands with this verb, for example Get, Set, New.
-Noun <noun>Only commands with this noun.
-Module <name>Only commands from one module.
<expression> | Get-MemberList the properties and methods of whatever object(s) came through the pipeline.

Everything in PowerShell is an object, not text, so Get-Member is the main way to discover what you can do with a result before writing the rest of a script.

Example

Get-Process | Get-Member -MemberType Property

Options

-MemberType PropertyOnly properties, not methods.
-StaticStatic members of the type instead of the instance.
Update-HelpDownload the latest help files for installed modules.

Help files are not included by default on a fresh install. Run this once (as Administrator) so Get-Help and -Online have real content.

Careful: Requires internet access and, the first time, an elevated session.
Get-ExecutionPolicy -ListShow the script execution policy for each scope.

Controls whether .ps1 scripts are allowed to run at all. Change it with Set-ExecutionPolicy, most safely at the CurrentUser scope.

Example

Set-ExecutionPolicy -Scope CurrentUser RemoteSigned

Options

RestrictedNo scripts at all (common default on Windows PowerShell 5.1).
RemoteSignedLocal scripts run freely; downloaded scripts need a trusted signature.
BypassNo restriction and no warnings.
Careful: This is a convenience control, not a security boundary: it only affects double-clicking or running .ps1 files directly, not every way code can execute.
$PROFILEShow the path to your current PowerShell profile script.

A profile script runs automatically at the start of every session, a common place for aliases, functions and module imports. PowerShell 7 and Windows PowerShell 5.1 use separate profile files, so settings do not carry over automatically.

Example

notepad $PROFILE
Get-ChildItem [path]List files and folders. Aliased as ls, dir and gci.

Works on the file system, but also on other PowerShell drives such as the registry (HKLM:\) or environment variables (Env:\).

Example

Get-ChildItem -Recurse -Filter *.log | Select-Object -First 10

Options

-RecurseInclude subfolders.
-Filter <pattern>Fast, provider-level wildcard filter.
-FileOnly files.
-DirectoryOnly folders.
-ForceInclude hidden and system items.
Set-Location <path>Change the current directory. Aliased as cd and sl.

Also works on non-filesystem drives, which is how you โ€œcdโ€ into the registry.

Example

Set-Location -Path HKLM:\SOFTWARE
Copy-Item <source> <destination>Copy a file or folder.

Options

-RecurseRequired to copy a folder with its contents.
-ForceOverwrite an existing destination and copy read-only or hidden items.
Move-Item <source> <destination>Move or rename a file or folder.

Moving to a new name in the same folder is how you rename something.

Remove-Item <path>Delete a file or folder.

Options

-RecurseRequired to delete a non-empty folder.
-ForceDelete hidden, read-only or system items without prompting.
-WhatIfPreview what would be deleted, without deleting it.
Careful: There is no recycle bin here: Remove-Item deletes permanently. Run with -WhatIf first when the path is built from a variable or wildcard.
New-Item -Path <path> -ItemType <type>Create a new file, folder, or other item.

Example

New-Item -Path .\notes.txt -ItemType File

Options

-ItemType DirectoryCreate a folder.
-ItemType FileCreate an empty file.
-Value <text>Initial content for a new file.
Test-Path <path>Check whether a file, folder or registry key exists. Returns True or False.

The usual guard before reading a file or creating one only if it is missing.

Example

if (-not (Test-Path .\out)) { New-Item -ItemType Directory .\out }
Get-Content <path>Read a text file, one line per pipeline object. Aliased as cat, gc and type.

Example

Get-Content .\app.log -Tail 20 -Wait

Options

-Tail <n>Only the last n lines.
-WaitKeep the file open and show new lines as they are written, like tail -f.
-RawRead the whole file as one string instead of a line array.
Set-Content <path> -Value <text>Write text to a file, replacing its contents.

Add-Content appends instead of replacing. Out-File is similar but designed to receive pipeline output rather than a -Value string.

Options

-Encoding UTF8Set the text encoding explicitly, since the default differs between Windows PowerShell 5.1 (UTF-8 with BOM) and PowerShell 7 (UTF-8 without BOM).
<expression> | Select-Object <properties>Pick specific properties, or the first/last N objects.

Example

Get-Process | Select-Object Name, CPU -First 5

Options

-First <n>Only the first n objects.
-Last <n>Only the last n objects.
-ExpandProperty <name>Return the raw values of one property instead of objects.
-UniqueRemove duplicate rows after the selection.
<expression> | Where-Object { <condition> }Filter pipeline objects by a condition. Aliased as where and ?.

$_ refers to the current object. A simplified syntax also works for simple comparisons: Where-Object CPU -gt 10.

Example

Get-Process | Where-Object { $_.CPU -gt 10 }
<expression> | Sort-Object <property>Sort pipeline objects by one or more properties.

Example

Get-ChildItem | Sort-Object Length -Descending

Options

-DescendingLargest or last first.
-UniqueRemove duplicates after sorting.
<expression> | ForEach-Object { <script> }Run a script block once per pipeline object. Aliased as % and foreach.

Different from the foreach statement (foreach ($x in $list) {}): ForEach-Object processes one item at a time as it arrives in the pipeline, which uses much less memory for large collections.

Example

Get-ChildItem *.txt | ForEach-Object { Rename-Item $_ ($_.Name + ".bak") }
<expression> | Group-Object <property>Group pipeline objects by a property and count each group.

Example

Get-Process | Group-Object Company | Sort-Object Count -Descending
<expression> | Measure-Object <property>Count objects, or sum/average/min/max a numeric property.

Example

Get-ChildItem *.log | Measure-Object -Property Length -Sum

Options

-SumTotal of the property.
-AverageAverage value.
-MaximumLargest value.
-MinimumSmallest value.
<expression> | Format-Table -AutoSizeFormat objects as a table in the console.

Only for display: the output becomes text, so do not pipe it into another cmdlet that expects objects. Format-List shows one property per line instead, better for objects with many properties.

Options

-AutoSizeSize columns to fit the content.
-WrapWrap long values instead of truncating them.
<expression> | ConvertTo-JsonSerialize objects to a JSON string.

Example

Get-Process | Select-Object Name, Id | ConvertTo-Json -Depth 3

Options

-Depth <n>How many levels of nested objects to include (default 2, often too shallow for complex objects).
<expression> | Export-Csv <path> -NoTypeInformationWrite objects to a CSV file.

-NoTypeInformation drops the #TYPE header line. On PowerShell 7 it is the default and the switch is unnecessary, but harmless to include for scripts shared with Windows PowerShell 5.1.

Example

Get-Process | Export-Csv processes.csv -NoTypeInformation
Get-ProcessList running processes.

Example

Get-Process -Name chrome | Sort-Object CPU -Descending

Options

-Name <name>Filter by process name.
-Id <pid>Get one process by its process ID.
Stop-Process -Id <pid>End a running process.

Options

-Name <name>Stop by process name instead of ID (stops every matching process).
-ForceStop a process that would otherwise prompt for confirmation.
Careful: Unsaved work in that process is lost. Prefer closing the application normally when possible.
Get-ServiceList Windows services and their status. Not available on Linux or macOS.

Example

Get-Service -Name wuauserv

Options

-Name <name>Filter by service name (wildcards allowed).
-DisplayName <name>Filter by the friendly display name.
Restart-Service -Name <name>Restart a Windows service.

Start-Service and Stop-Service do the same for just starting or stopping. Requires an elevated session for most system services.

Get-WinEvent -LogName System -MaxEvents 50Read entries from a Windows event log.

Get-WinEvent replaces the older Get-EventLog, which only reads classic logs and is not available in PowerShell 7 on non-Windows systems (and is deprecated even on Windows).

Example

Get-WinEvent -FilterHashtable @{ LogName = "Security"; Id = 4625 } -MaxEvents 20

Options

-FilterHashtableEfficient server-side filtering by log name, event ID, level or time.
-MaxEvents <n>Limit how many entries are returned.
Restart-ComputerRestart the computer, locally or on a remote one.

Options

-ComputerName <name>Restart a remote computer (needs permission and remoting enabled).
-ForceRestart even if users are logged on, without waiting.
Careful: Closes everything running on that computer. Save work and warn other users on shared or remote machines first.
Get-HotFixList installed Windows updates.

Windows-only. For driver and feature update history, Windows Update's own history view is more complete than Get-HotFix.

$name = <value>Create or update a variable.

Variable names are not case-sensitive. No declaration keyword is needed; the first assignment creates it.

Example

$count = 5
$name = "web-server-01"
"text $variable text"Insert a variable into a string. Only works inside double quotes, not single quotes.

For a property or expression, wrap it: "Count is $($list.Count)". Single-quoted strings are literal and never interpolate.

Example

"Server $name has $count cores"
if (<condition>) { } elseif (<condition>) { } else { }Conditional branching.

Comparison uses operators like -eq, -ne, -gt, -lt, -like and -match, not ==, !=, >, <, which PowerShell parses differently (as redirection in some contexts).

Example

if ($count -gt 10) { "many" } elseif ($count -gt 0) { "some" } else { "none" }
foreach ($item in $collection) { }Loop over a collection, loading it into memory first.

For very large or streamed input, ForEach-Object in a pipeline is usually more memory-efficient.

Example

foreach ($file in Get-ChildItem *.log) { Write-Host $file.Name }
function Verb-Noun { param($x) ... }Define a reusable function.

Community convention is an approved Verb-Noun name (see Get-Verb) so your function behaves like a built-in cmdlet and is easy to discover.

Example

function Get-FileAge {
  param([string]$Path)
  (Get-Date) - (Get-Item $Path).LastWriteTime
}
try { } catch { } finally { }Handle errors that would otherwise stop the script.

Only catches terminating errors. Many cmdlets write non-terminating errors instead; add -ErrorAction Stop to force a cmdlet call to throw one that try/catch can catch.

Example

try {
  Get-Item nonexistent.txt -ErrorAction Stop
} catch {
  Write-Warning $_.Exception.Message
}
-eq -ne -gt -ge -lt -leEquality and comparison operators.

Case-insensitive by default for strings. Prefix with c for case-sensitive (-ceq) or i to be explicit about case-insensitive (-ieq).

Options

-eq / -neEqual / not equal.
-gt / -geGreater than / greater than or equal.
-lt / -leLess than / less than or equal.
-like / -notlikeWildcard match with * and ?.
-match / -notmatchRegular expression match.
Get-InstalledModuleList modules installed from the PowerShell Gallery (via PowerShellGet).

Get-Module -ListAvailable shows every module PowerShell can find, including built-in ones; Get-InstalledModule is scoped to what you installed yourself.

Install-Module -Name <name> -Scope CurrentUserDownload and install a module from the PowerShell Gallery.

Options

-Scope CurrentUserInstall for your user only, no elevation needed.
-Scope AllUsersInstall machine-wide; needs an elevated session.
-ForceReinstall or install without confirmation prompts.
Careful: Modules from the Gallery are community-published. Check the publisher and download count before installing something you depend on for production use.
Import-Module <name>Load a module into the current session.

Most modules auto-load the first time one of their commands is used, so this is mainly needed for modules that do not support auto-loading, or to load a specific version.

Invoke-Command -ComputerName <name> -ScriptBlock { }Run a script block on a remote computer over WS-Management (PowerShell Remoting).

Requires PowerShell Remoting to be enabled on the target (Enable-PSRemoting) and, usually, administrative rights there. On the target machine the script runs under Windows PowerShell 5.1 unless the target also has PowerShell 7 remoting configured.

Example

Invoke-Command -ComputerName srv01 -ScriptBlock { Get-Service -Name wuauserv }

Options

-Credential <cred>Run as a different user on the remote computer.
-ComputerName <names>One or more target computers, run in parallel.
Enter-PSSession -ComputerName <name>Open an interactive remote session, similar to SSH.

Exit-PSSession or exit returns to the local session. For running the same command on many computers at once, Invoke-Command is usually a better fit than looping Enter-PSSession.

Get-CredentialPrompt for a username and password, returned as a PSCredential object.

Pass the result to a cmdlet's -Credential parameter. The password is stored as a SecureString in memory, not as plain text, but it is still decrypted when the target cmdlet uses it.

Example

$cred = Get-Credential
Invoke-Command -ComputerName srv01 -Credential $cred -ScriptBlock { whoami }

The descriptions in this reference are currently in English.

About this tool

Search or filter by group and copy a cmdlet with one click. Open a cmdlet to see what it does, an example, its main parameters and warnings where it can do damage. Commands work on both Windows PowerShell 5.1 and PowerShell 7 unless noted otherwise.

๐Ÿ”’ Your input stays in your browser and is never sent anywhere.

Frequently asked questions

Should I learn Windows PowerShell 5.1 or PowerShell 7?

For new scripts, PowerShell 7: it is actively developed and runs on Windows, Linux and macOS. Windows PowerShell 5.1 still ships with Windows and some Windows-only modules (like many ActiveDirectory cmdlets) only load there.

What to do next

Also useful

Found a problem or have a suggestion? Tell us