Essential PowerShell Cheat Sheet

PowerShell is a powerful scripting language and command-line interface (CLI) developed by Microsoft. It’s built on the .NET Framework and is primarily used to automate administrative tasks, manage system configurations, and streamline IT operations. Think of it as the Windows equivalent of Bash in Linux—but with a twist: PowerShell is object-oriented, making it more versatile for developers and system admins alike.

  • Object-Oriented Language (OOP): Unlike traditional shells, PowerShell works with objects, not plain text.
  • Cross-Platform: Although native to Windows, it can also run on Linux (via package managers) and macOS (via Homebrew or manual installation).
  • Extensive Scripting Capabilities: Scripts in PowerShell use the .ps1 file extension and are composed of small command units called cmdlets (pronounced “command-lets”).
  • Writing and editing scripts
  • Running and testing cmdlets
  • Debugging with features like breakpoints and syntax highlighting

In Windows, PowerShell is case-insensitive by default. However, this doesn’t always hold true on other platforms like Linux or macOS—so be careful when scripting cross-platform!

PowerShell has a vast library of commands, so understanding its syntax is key. Knowing how to structure commands, use parameters, and manipulate objects will unlock its full power.

PowerShell CommandAlias(es)Description
Get-Help(None)Displays help info for any command. Try Get-Help Get-Process to learn more about it.
Get-Command(None)Lists all available PowerShell commands. Great for discovering what’s available.
Get-ChildItemdir, ls, gciLists files and folders in the current directory.
Get-Locationpwd, glShows your current working directory.
Set-Locationcd, chdir, slChanges your working directory.
Get-Contentcat, gc, typeDisplays the content of a file.
Copy-Itemcopy, cp, cpiCopies files or directories.
Remove-Itemdel, rm, riDeletes files or directories.
Move-Itemmove, mv, miMoves files or directories to a new location.
New-ItemniCreates a new file or folder.
Out-File>, >>Redirects output to a file. Use Out-File when you need to specify extra options.
Invoke-WebRequestcurl, iwr, wgetFetches content from a web page—super useful for scripts and automation.
Write-Outputecho, writeSends output to the screen or next command in a pipeline.
Clear-Hostcls, clearClears the terminal screen for a clean view.

Example: Using a Few Command Together

Set-Location C:\Logs
Get-ChildItem *.log | Get-Content | Out-File CombinedLogs.tx

This script navigates to the Logs directory, grabs all .log files, reads their contents, and saves them to a single file.

Parameters are command-line arguments you can pass to PowerShell commands to customize how they run. They make your scripts dynamic, flexible, and reusable.

Example syntax:

powershellCopyEditDo-Something -Parameter1 value1 -Parameter2

In this example:

  • Parameter1 takes a specific value.
  • Parameter2 is a switch — it doesn’t require a value.

Want to find all commands that accept a specific parameter? Use this helpful trick:

powershellCopyEditGet-Help * -Parameter ComputerName

PowerShell includes built-in parameters that help you avoid accidental changes or deletions.

ParameterDescriptionExample
-ConfirmPrompts you before executing the actionNew-Item test.txt -Confirm
-WhatIfSimulates the action and shows what would happen without making changesRemove-Item test.txt -WhatIf

These are especially useful when testing or running scripts that modify system files or settings.

The pipeline character (|) allows you to chain commands together. It sends the output of one command into the next command in the sequence—similar to Bash or Splunk scripting.

Basic syntax:

powershellCopyEditCommand1 | Command2 | Command3

Real-world example:

powershellCopyEditGet-Service |
Where-Object -Property Status -EQ Running |
Select-Object Name, DisplayName, StartType |
Sort-Object -Property StartType, Name
  1. Get-Service: Gets a list of all Windows services.
  2. Where-Object: Filters services with a Status of Running.
  3. Select-Object: Selects only Name, DisplayName, and StartType properties.
  4. Sort-Object: Sorts the output first by StartType, then by Name.

These core concepts—parameters and pipes—are the building blocks for writing clean, powerful PowerShell scripts. Mastering them opens the door to advanced automation.

Pipelines let you chain multiple commands together by passing the output from one to the next. Here are a couple more examples to illustrate how versatile this can be:

CommandDescription
"plan_A.txt" | Rename-Item -NewName "plan_B.md"Renames the file plan_A.txt to plan_B.md.
Get-ChildItem | Select-Object basename | Sort-Object *Lists the names (base names only) of all files in the current directory, sorted alphabetically.

These examples showcase how SOC analysts, system admins, and threat hunters can harness the power of pipes in everyday scenarios.

CommandWhat It Does
Get-Process | Where-Object { $_.CPU -gt 100 }Lists processes consuming more than 100 CPU seconds.
Get-EventLog -LogName Security -Newest 50 | Select-Object TimeGenerated, EntryType, MessageDisplays the 50 most recent Security event logs with key details.
Get-Service | Where-Object { $_.Status -eq "Stopped" } | Sort-Object NameLists all stopped services and sorts them alphabetically.
Get-ChildItem C:\Logs -Recurse | Where-Object { $_.Extension -eq ".log" } | Select-Object Name, LastWriteTimeRecursively searches for .log files and displays their names and last modified time.
Get-LocalUser | Select-Object Name, Enabled | Where-Object { $_.Enabled -eq $false }Finds all local user accounts that are disabled.

Use Case Tip: These piped commands can be embedded into larger scripts for automation, incident response, or reporting.

PowerShell treats everything as an object—a fundamental unit that includes both properties and methods, just like in C#, Java, or Python.

  • Accessing object properties or methods: Use a dot (.) powershellCopyEdit(Get-Service -Name Fax).Status # Returns the status of the Fax service (Get-Service -Name Fax).GetType() # Returns the object type (ServiceController)
  • Discover object members (properties/methods): powershellCopyEditGet-Service -Name Fax | Get-Member

Variables are used to store data, similar to other programming languages.

CommandDescription
New-Variable var1Creates a variable named var1
Get-Variable my*Lists variables starting with my
Remove-Variable bad_variableDeletes a variable named bad_variable
$var = "string"Assigns a string to a variable
$a,$b = 0Assigns the same value 0 to $a and $b
$a,$b,$c = 'a','b','c'Assigns respective values to each variable
$a,$b = $b,$aSwaps values of $a and $b
$var = [int]5Enforces variable to store only integers
VariableDescription
$HOMEPath to user’s home directory
$NULLRepresents null/empty value
$TRUEBoolean true
$FALSEBoolean false
$PIDProcess ID of the current PowerShell session

Regular expressions are patterns used to match character combinations in strings.

SyntaxMeaning
[aeiou]Match any single vowel
[^aeiou]Match any non-vowel
[A-Z]Uppercase characters
\d / \DDigit / Non-digit
\w / \WWord char (letter, digit, _) / Non-word
\s / \SWhitespace / Non-whitespace
.Any character except newline
*, +, ?Zero/more, one/more, zero/one occurrences
{n,m}Match between n and m times
powershellCopyEdit"str" -Match '[aeiou]'    # True if it contains a vowel
"data.txt" -NotMatch '\.exe$' # True if it doesn’t end with .exe
"Word" -CMatch 'word' # Case-sensitive match
OperatorDescriptionExampleResult
+Addition$a + $b30
-Subtraction$a - $b-10
*Multiplication$a * $b200
/Division$b / $a2
%Modulus$b % $a0
OperatorMeaningExampleResult
-eqEqual$a -eq $bFalse
-neNot equal$a -ne $bTrue
-gtGreater than$b -gt $aTrue
-ltLess than$a -lt $bTrue
OperatorDescriptionExampleResult
-andLogical AND$a -and $bTrue
-orLogical OR$a -or 0True
!NOT!($a -eq 10)False
-xorExclusive OR$a -xor $bFalse
OperatorDescriptionExample
=Assign$c = $a + $b
+=Add & assign$c += $a
-=Subtract & assign$c -= $a

Control where output goes:

OperatorDescriptionExample
>Overwrite to file/output devicecommand > out.txt
>>Append output to filecommand >> log.txt
2>&1Redirect error to standard outputcommand 2>&1 > all_output.txt
PrefixStreamExample
1>Standard outputDo-Something 1>> result.txt
2>Standard errorcommand 2> error.log
3>WarningsDo-Something 3> warnings.log
4>Verbose outputDo-Something 4>> verbose.txt
5>Debug messagesDo-Something 5>&1
6>Info (PS 5.0+)Do-Something 6>$null
OperatorDescriptionExample
-LikeWildcard match"file.txt" -Like "*.txt"
-MatchRegex match"log01" -Match '\d'
-ContainsCollection contains a value@("a", "b") -Contains "a"
-InValue exists in a collection"a" -In @("a", "b")
SymbolDescriptionExample
()Group expressions(1+1)*24
$()Return result of expression"Today is $(Get-Date)"
@()Return results as an array`@(Get-ChildItem
[]Type conversion[int] "5"5
&Run a command/pipeline& 'Get-Process' (PowerShell 6.0+)

Use comments to document your scripts and escape special characters for formatting.

SymbolDescriptionExample
#Single-line comment# This is a comment
<# ... #>Multi-line comment<# Block comment here #>
EscapeOutput
"`"Escaped double quote
`tTab
`nNew line
`Line continuation

Enumeration is the process of extracting information such as users, groups, resources, and other interesting data from a system.
Here’s a table of essential enumeration commands every pentester should know:

CommandDescription
net accountsRetrieve the system’s password policy.
whoami /privView the privileges of the currently logged-in user.
ipconfig /allList all network interfaces, IP addresses, and DNS settings.
Get-LocalUser | Select *List all local users on the machine.
Get-NetRouteDisplay IP route information from the system’s routing table.
Get-CommandList all available PowerShell commands.

Enumeration is the process of extracting information such as users, groups, resources, and other interesting data from a system.
Here’s a table of essential enumeration commands every pentester should know:

CommandDescription
net accountsRetrieve the system’s password policy.
whoami /privView the privileges of the currently logged-in user.
ipconfig /allList all network interfaces, IP addresses, and DNS settings.
Get-LocalUser | Select *List all local users on the machine.
Get-NetRouteDisplay IP route information from the system’s routing table.
Get-CommandList all available PowerShell commands.

PowerShell is built for automation, especially for system administration. Here’s a list of useful cmdlets for daily sysadmin tasks:

CommandDescription
New-PSDrive -Name "L" -PSProvider FileSystem -Root "\\path\to\data" -PersistMounts a network drive (don’t use C:)
Enable-PSRemotingEnables remote PowerShell access
Invoke-Command -ComputerName pc01, pc02 -ScriptBlock {cmd /c setup.exe}Run batch scripts remotely
Get-HotfixLists installed software patches
$Password = Read-Host -AsSecureString + New-LocalUser "User03" -Password $PasswordAdds a new local user
Get-ProcessLists current processes
Start-Sleep 10Pauses script for 10 seconds
Start-Job, Receive-JobManage background jobs
New-PSSession, Get-PSSessionCreate/view remote sessions
Enable-NetFirewallRuleEnable a disabled firewall rule
ConvertTo-HtmlConvert objects to HTML format
Invoke-RestMethodCall a REST API endpoint
powershellCopyEditGet-ChildItem C:\data -Recurse | 
? { !$_.PsIsContainer -and $_.LastWriteTime -gt (Get-Date).Date } |
% { Copy-Item -Path $_.FullName -Destination "\\path\to\backup" }

Final Thoughts on PowerShell

PowerShell’s flexibility makes it an indispensable tool for anyone in the IT field. Whether you’re a security analyst, pen tester, developer, sysadmin, or just beginning your automation journey, PowerShell belongs in your toolkit. Have any favorite PowerShell tricks or tools you use? Drop them in the comments below, and let’s chat about them!

LinkedIn
X
Facebook

Related Articles

Leave a Comment

Your email address will not be published. Required fields are marked *

Copyright © 2025 Yakubu Bello - Cyber Security Expert