Powershell cheat sheet
Powershell cheat sheet
What Is PowerShell?
The PowerShell Integrated Scripting Environment (ISE) is a terminal console for running
PowerShell commands known as cmdlets (pronounced “Command-let”) and
writing/executing PowerShell scripts with the file extension “.ps1”.
PowerShell commands are case-insensitive in its native Windows environment, but that is
not true for other operating systems. Read more about PowerShell case sensitivity here.
Operating Action
system
Windows 1. Right-click Start > select “Windows PowerShell”
2. If you want elevated privileges, select ”Windows PowerShell
(Admin)”
3. Run Command Prompt (click Start > type cmd) > input
“PowerShell” and select your preferred option—with or without
“(Admin)”
Linux Raspberry Pi: In Terminal, type ~/powershell/pwsh > press Enter.
PowerShell syntax
PowerShell is so complex and contains so many commands that you need to understand its
syntax to use it well.
Parameters
Parameters are command arguments that enable developers to build reusable PowerShell
scripts. For a command with two parameters (here, Parameter1 takes a value, but
Parameter2 doesn’t), the syntax is:
Do-Something -Parameter1 value1 -Parameter2
The following are risk mitigation parameters that apply to all PowerShell commands:
ni test.txt -Confirm
-WhatIf Displays what a certain command Removal of an item called
would do. test.txt:
Pipes
PowerShell uses the pipe character “|” to pass the output of a series of commands to
subsequent commands as pipeline input, analogous to scripting in Bash and Splunk. For a
sequence containing three commands, the PowerShell pipeline syntax is:
In this example, Get-Service sends a list of all the Windows services to Where-Object,
which filters out the services having Running as their Status. The filtered results pass
through Select-Object, which picks out the columns Name, DisplayName, and
StartType, and finally, Sort-Object sorts these columns by StartType and Name.
Other examples of pipes:
Command Description
"plan_A.txt" | Rename-Item Rename the file “plan_A.txt” to a new name
-NewName "plan_B.md" “plan_B.md”
Get-ChildItem | Select-Object Lists the names of all the files in the current
basename | Sort-Object * working directory, sorted in alphabetical order.
Objects
An object is a data type that consists of object properties and methods, either of which you
can reference directly with a period (.) followed by the property/method name. PowerShell
contains .NET Framework objects like other OOP languages such as C#, Java, and Python.
Variables
These are the basic commands for defining and calling PowerShell variables.
Command Description
New-Variable var1 Create a new variable var1 without defining its value
Get-Variable my* Lists all variables in use beginning with “my*”
Remove-Variable Delete the variable called “bad_variable”
bad_variable
$var = "string" Assign the value "string" to a variable $var
$a,$b = 0 Assign the value 0 to the variables $a,$b
$a,$b,$c = 'a','b','c' Assign the characters 'a','b','c' to
respectively-named variables
$a,$b = $b,$a Swap the values of the variables $a and $b
$var = [int]5 Force the variable $var to be strongly typed and only
admit integer values
Variable Description
$HOME Path to user's home directory
$NULL Empty/null value
$TRUE Boolean value TRUE
$FALSE Boolean value FALSE
$PID Process identifier (PID) of the process hosting the current session of
PowerShell
Regular Expressions
Regex Description
syntax
[ ] Allowable characters, e.g., [abcd] means 'a'/'b'/'c'/'d'
[aeiou] Single vowel character in English
^ 1. Use it with square brackets [ ] to denote exclusion
2. For matching the beginning of a string
[^aeiou] Single consonant character in English
$ For matching the end of a string
- Use with square brackets [ ] to denote character ranges
[A-Z] Uppercase alphabetic characters
[a-z] Lowercase alphabetic characters
[0-9] Numeric characters
[ -~] All ASCII-based (hence printable) characters
\t Tab
\n Newline
\r Carriage return
. Any character except a newline (\n) character; wildcard
* Match the regex prefixed to it zero or more times.
+ Match the regex prefixed to it one or more times.
? Match the regex prefixed to it zero or one time.
{n} A regex symbol must match exactly n times.
{n,} A regex symbol must match at least n times.
{n,m} A regex symbol must match between n and m times inclusive.
\ Escape; interpret the following regex-reserved characters as the
corresponding literal characters: []().\^$|?*+{}
\d Decimal digit
\D Non-decimal digit, such as hexadecimal
\w Alphanumeric character and underscore (“word character”)
\W Non-word character
\s Space character
\S Non-space character
The following syntax is for checking strings (enclosed with quotes such as 'str' or "ing")
against regexes:
Here are examples of strings that match and don’t match the following regular expressions:
Note that -Match is not concerned with case sensitivity. For that, you will want to use
-CMatch and -CNotMatch
Operators
PowerShell has many operators. Here we present the most commonly used ones.
In the examples below, the variables $a and $b hold the values 10 and 20, respectively. The
symbol → denotes the resulting value, and ⇔ denotes equivalence.
Arithmetic operators:
Comparison operators:
Assignment operators:
$c = $a + $b
+= Add the right side operand to the left operand $c += $a ⇔ $c = $c +
and assign the result to the left-hand operand. $a
-= Subtract the right side operand from the left $c -= $a ⇔ $c = $c -
operand and assign the result to the left-hand $a
operand.
Logical operators:
Operator Description
> Send output to the specified file or output device.
Do-Something 3>
warning.txt
4 Verbose output Append verbose.txt with the
verbose output:
Do-Something 4>>
verbose.txt
5 Debug messages Send debugging output to standard
error:
Do-Something 5>&1
6 Information (PowerShell 5.0+) Suppress all informational output:
Do-Something 6>$null
Get-ChildItem | Where-Object
{$_.name -NotLike "*.bat"}
-Match, Check if a string The following examples evaluate to TRUE:
-NotMatch matches a regex
pattern (or not) 'blog' -Match 'b[^aeiou][aeiuo]g'
@("Au","Ag","Cu") -NotContains
"Gold"
-In, -NotIn Check if a value is The following examples evaluate to TRUE:
(not) in a collection
"blue" -In @("red", "green",
"blue")
Miscellaneous operators:
(1+1)*2
$() Get the result of one or more Get today’s date and time:
statements
"Today is $(Get-Date)"
@() Get the results of one or more Get only file names in the current
statements in the form of arrays working directory:
@(Get-ChildItem |
Select-Object Name)
[] Converts objects to the specific type Check that there are 31 days
between January 20 and February
20, 1988:
[DateTime] '2/20/88' -
[DateTime] '1/20/88' -eq
[TimeSpan] '31'
# True
& Run a command/pipeline as a Get-Process -Name pwsh &
Windows Powershell background job
(PowerShell 6.0+)
Hash Tables
A hash table (alternative names: dictionary, associative array) stores data as key-value
pairs.
Comments
Comments help you organize the components and flow of your PowerShell script.
for($i=1; $i -le
10;
$i++){Write-Host
$i}
ForEach ($<Item> in ForEach-Object Display the file size of
$<Collection>){<Statement loop; enumeration each file in the current
list>} over Items in a working directory:
Collection.
Get-ChildItem | %
The alias for {Write-Host
“ForEach” is “%”. $_.length $_.name
The alias “$_” -separator "`t`t"}
represents the
current object.
While While-loop. In each iteration,
(<Condition>){<Statement increment $a by one and
list>} print its value unless/until
this value becomes 3:
while($a -ne 3)
{
$a++
Write-Host $a
}
If (<Test1>) {<Statement list Conditional Compares the value of
1>} [ElseIf (<Test2>) statement. $a against 2:
{<Statement list 2>}] [Else
{<Statement list 3>}] if ($a -gt 2) {
Write-Host
"The value $a is
greater than 2."
} elseif ($a -eq
2) {
Write-Host
"The value $a is
equal to 2."
} else {
Write-Host
("The value $a is
less than 2 or" +
" was not
created or
initialized.")
}
The following table lists PowerShell commands (change the parameters and values as
appropriate) tailored to administrative tasks:
Command Description
New-PSDrive –Name "L" Set up network drives.
–PSProvider FileSystem
–Root "\\path\to\data" Specify an unused capital letter (not C:) as the
–Persist “-Name” of a drive, and point the “-Root”
parameter to a valid network path.
Enable-PSRemoting Enable PowerShell remoting on a computer.
Command Description
Set-ExecutionPolicy -ExecutionPolicy Bypass In this powerful command,
“Bypass” means removing
all obstacles to running
commands/scripts and
disabling warnings and
prompts.
ExecutionPolicy myth:
If you configure it a certain
way, it will automatically
protect your device from
malicious activities.
ExecutionPolicy fact:
It’s a self-imposed fence on
PowerShell
commands/scripts by a
user, so if a malicious
PowerShell script has
caused damage, you
already have a
compromised machine.
A typical workaround is
obfuscation, such as
creating dummy variables
to hold values in the script
and Base64-encoding
these values. Good
obfuscation makes it
harder for AMSI to
recognize a script.
But a tried-and-tested
workaround that doesn’t
involve obfuscation is
splitting it up into separate
lines.
Enumeration Commands
To enumerate is to extract information, including users, groups, resources, and other
interesting fields, and display it. Here is a table of essential enumeration commands:
Command Description
net accounts Get the password policy
whoami /priv Get the privileges of the currently logged-in user
ipconfig /all List all network interfaces, IP, and DNS
Get-LocalUser | Select * List all users on the machine
Get-NetRoute Get IP route information from the IP routing table
Get-Command List all PowerShell commands
You may come across PowerShell modules and scripts such as Active Directory,
PowerView, PowerUp, Mimikatz, and Kekeo, all of which pentesters use. We encourage you
to learn them independently.
Conclusion
This PowerShell cheat sheet is a brief but handy guide to navigating PowerShell, whether as
a beginner or as a seasoned administrator. If you want to learn more about PowerShell,
check out our courses on Windows Server and Azure to see it in action, and we’d love to
hear what other PowerShell functions you’d like to learn in the comments below.