Starting with Windows PowerShell Cheatsheet
Starting with Windows PowerShell Cheatsheet
POWERSHELL
Preface 1
Introduction 1
Purpose and Benefits of PowerShell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Versions of PowerShell. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Installing PowerShell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Architecture 1
Command Line Interface vs Graphical User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Cmdlets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Objects and Pipelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Scripts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
The Language 9
Syntax and Grammar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Variables and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Wildcards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Error Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
PREFACE
PREFACE SYSTEM REQUIREMENTS
This cheatsheet provides an overview of the most The system requirements for PowerShell vary
commonly used PowerShell commands, grouped by depending on the version and operating system
category. Whether you’re new to PowerShell or an being used. However, PowerShell 7.1 can run on
experienced user, this cheatsheet will serve as a Windows, macOS, and Linux systems.
handy reference guide for common tasks and
commands.
INSTALLING POWERSHELL
From basic file management to advanced system PowerShell is installed by default on most modern
administration, PowerShell can help you get things Windows operating systems. However, if it’s not
done more efficiently and effectively. This cheat installed, it can be downloaded and installed from
sheet is designed to help you quickly find the right the Microsoft website.
command for the job, so you can spend less time
searching for information and more time getting
KEY FEATURES
things done.
• PowerShell is a powerful scripting language
We hope this cheatsheet helps you become more
that allows administrators to automate tasks
productive with PowerShell. Happy scripting!
and create custom scripts.
ARCHITECTURE
ARCHITECTURE
PURPOSE AND BENEFITS OF
POWERSHELL COMMAND LINE INTERFACE VS
GRAPHICAL USER INTERFACE
PowerShell is designed to simplify and automate
administrative tasks in Windows environments. It The CLI interface provides users with greater
allows administrators to manage Windows systems flexibility, control, and automation capabilities,
more efficiently and effectively by providing a making it easier to perform repetitive
powerful, flexible, and scriptable command-line administrative tasks. With PowerShell,
interface. Some benefits of using PowerShell administrators can automate tasks such as
include improved productivity, reduced errors, and managing users and groups, configuring network
increased scalability. settings, and managing virtual machines.
However, for advanced administrative tasks, These are the basic cmdlets that are included in
PowerShell’s CLI is the preferred method, as it PowerShell by default. They provide core
provides more control and automation capabilities. functionality for working with files, directories,
The GUI interface can be a helpful tool for basic processes, and more.
system management tasks, but it can be time-
consuming for complex and repetitive tasks. Cmdlet Description
Cmdlet Description These cmdlets are used for managing SQL Server
objects, such as databases, tables, and views.
Get-Mailbox Lists mailboxes in
Exchange Server
Cmdlet Description
New-Mailbox Creates a new mailbox
Get-SqlDatabase Lists SQL Server
Set-Mailbox Modifies a mailbox databases
Networking cmdlets
SharePoint Server cmdlets
These cmdlets are used for working with network
These cmdlets are used for managing SharePoint settings, such as IP addresses, DNS servers, and
Server objects, such as sites, lists, and libraries. network adapters.
Get-NetIPAddress Retrieves IP address These cmdlets are used for working with storage
configuration devices and settings, such as disks, volumes, and
information for all IP file systems.
addresses assigned to
network adapters on the Cmdlet Description
computer. New-PSDrive Creates a PowerShell
Get-NetTCPConnection Retrieves a list of all drive that is connected
active TCP connections to a network resource or
on the computer. a storage device.
• Pipelines in PowerShell are used to pass objects • Modules can be loaded using the Import-Module
from one cmdlet to another, allowing complex cmdlet or automatically loaded when needed
operations to be performed on data without the based on module auto-discovery settings.
need for intermediate variables. For example,
• Once a module is loaded, its cmdlets and
the output of Get-Process can be passed to
functions can be used in the PowerShell
Select-Object to retrieve only the Name and CPU
session. For example, the Get-ADUser cmdlet in
properties, and then to Sort-Object to sort the
the ActiveDirectory module can be used to
results by CPU usage.
retrieve information about users in Active
• PowerShell’s pipeline supports both filtering Directory.
and sorting, as well as a variety of other
• Modules can be managed using the Get-Module,
operations such as grouping, joining, and
Import-Module, and Remove-Module cmdlets,
formatting. This allows users to perform
which allow users to list loaded modules, load
complex data manipulations using simple one-
new modules, and remove loaded modules,
liners.
respectively.
• PowerShell also supports the creation of
• Users can create their own modules using
custom objects using the New-Object cmdlet.
PowerShell scripts and manifest files. This
This allows users to create objects with custom
allows users to package their own cmdlets,
properties and methods, and then pass them to
functions, and other resources for easy
other cmdlets in the pipeline.
distribution and use by others.
• PowerShell’s object-oriented nature allows for
• Modules can also include other resources, such
easy integration with .NET Framework and
as scripts, configuration files, and help files,
other third-party libraries, allowing users to
which can be accessed using the Get-Command,
take advantage of existing code and APIs from
Get-Help, and Get-Content cmdlets, respectively.
within PowerShell scripts.
• PowerShell also supports module versioning,
• One important thing to note is that objects in
which allows users to load and use specific
PowerShell are not always compatible with
versions of a module, ensuring compatibility
other command-line tools that expect text-
with existing scripts and dependencies.
based input and output. In such cases,
PowerShell provides options for converting • Modules can be published to PowerShell
objects to text and vice versa, such as the galleries, such as the PowerShell Gallery or a
ConvertTo-Json and ConvertFrom-Json cmdlets private gallery, for easy sharing and
for working with JSON data. installation by others.
MODULES VARIABLES
Modules in PowerShell are collections of cmdlets, Variables in PowerShell are used to store and
functions, providers, and other resources that can manipulate data in scripts and interactive sessions.
be loaded and used in PowerShell. Modules allow PowerShell supports several different types of
users to extend the functionality of PowerShell variables, each with its own scope and lifetime.
beyond the built-in cmdlets and provide a way to
share code and functionality with others. Here are some key things to know about variables
in PowerShell:
Here are some key things to know about modules in
PowerShell: • Variables in PowerShell are represented using
a dollar sign $ followed by the variable name.
• PowerShell includes several built-in modules, For example, $myVariable is a valid variable
such as the ActiveDirectory module for name in PowerShell.
working with Active Directory, the Hyper-V • PowerShell supports several different types of
module for managing virtual machines, and the variables, including scalar variables (which
NetTCPIP module for working with TCP/IP store a single value), array variables (which
store multiple values of the same type), and function keyword, followed by the function
hash tables (which store key-value pairs). name, any parameters the function accepts,
and the body of the function enclosed in braces.
• Variables in PowerShell have a scope, which
For example, function MyFunction { Write-
determines where the variable is visible and
Output "Hello, World!" } defines a function
accessible. PowerShell supports several
called MyFunction that simply writes the string
different scopes, including global (which is
"Hello, World!" to the console.
visible throughout the entire session), local
(which is visible only within the current script • Functions in PowerShell can accept
or function), and script (which is visible parameters, which are used to pass data into
throughout the entire script but not outside of the function. Parameters are defined inside the
it). parentheses following the function name,
separated by commas. For example, function
• PowerShell also supports automatic variables,
MyFunction ($Name) { Write-Output "Hello,
which are predefined variables that hold
$Name!" } defines a function called MyFunction
system information such as the current user,
that accepts a parameter called $Name and
the last error message, and the current
writes a personalized greeting to the console.
directory.
• Functions in PowerShell can return values
• PowerShell allows variables to be assigned
using the return keyword. For example,
values using the = operator. For example,
function Add-Numbers ($a, $b) { return $a +
$myVariable = "Hello, World!" assigns the
$b } defines a function called Add-Numbers that
string "Hello, World!" to the variable
accepts two parameters, adds them together,
$myVariable.
and returns the result.
• PowerShell also supports variable expansion,
• Functions in PowerShell can be saved to disk as
which allows variables to be used inside strings
script files, just like regular PowerShell scripts.
and other commands. Variable expansion is
This allows you to reuse functions across
done using the $() syntax. For example, "The
different scripts and sessions.
value of my variable is $($myVariable)" would
expand to "The value of my variable is Hello, • PowerShell supports several different types of
World!" if $myVariable was assigned the string functions, including advanced functions (which
"Hello, World!". provide additional features like parameter
validation and pipeline input), script functions
• PowerShell allows variables to be passed
(which allow you to define a function as a
between cmdlets and functions using the
separate script file), and anonymous functions
pipeline. For example, Get-ChildItem | Where-
(which are defined inline as part of a larger
Object {$_.Name -like "*.txt"} | Select-
command).
Object FullName retrieves a list of files, filters
the list to include only files with a .txt • PowerShell functions can be called from other
extension, and then returns the full path of functions, scripts, or interactive sessions,
each file as a string object to the pipeline. These making them a powerful tool for building
string objects can then be assigned to a variable complex automation workflows.
for further processing or manipulation.
SCRIPTS
FUNCTIONS
Scripts in PowerShell are text files that contain a
Functions in PowerShell are reusable blocks of code series of PowerShell commands and statements.
that perform a specific task. They allow you to write They allow you to automate tasks by running the
complex scripts more easily by breaking them same set of commands multiple times, or by
down into smaller, more manageable pieces. running them on a schedule.
Here are some key things to know about functions Here are some key things to know about scripts in
in PowerShell: PowerShell:
• Functions in PowerShell are defined using the • PowerShell scripts are saved as plain text files
with a .ps1 file extension. They can be edited in computer and the remote computer. WinRM
any text editor, including the built-in must be enabled and configured on both the
PowerShell Integrated Scripting Environment local and remote computers before PowerShell
(ISE). Remoting can be used.
• PowerShell scripts are executed by invoking • PowerShell Remoting can be initiated from the
the powershell.exe executable and passing the local computer using the Enter-PSSession
script file as a command-line argument. For cmdlet or the Invoke-Command cmdlet. Enter-
example, powershell.exe -File PSSession creates an interactive session with
C:ScriptsMyScript.ps1 runs a script file called the remote computer, allowing you to enter
MyScript.ps1 located in the C:Scripts directory. commands as if you were physically present at
the remote computer. Invoke-Command executes a
• PowerShell scripts can contain any valid
single command or script on the remote
PowerShell command or statement, including
computer and returns the results to the local
cmdlets, functions, variables, loops, and
computer.
conditional statements. They can also include
comments, which are denoted by the # symbol. • PowerShell Remoting requires that you have
administrative privileges on both the local and
• PowerShell scripts can accept parameters,
remote computers in order to establish a
which are used to pass data into the script.
connection and execute commands. You must
Parameters are defined using the param
also have the appropriate permissions to access
keyword at the beginning of the script,
and modify the resources on the remote
followed by the parameter names enclosed in
computer.
parentheses. For example, param($Name) Write-
Output "Hello, $Name!" defines a script that • PowerShell Remoting supports several
accepts a parameter called $Name and writes a authentication methods, including Kerberos,
personalized greeting to the console. Negotiate, and Basic authentication. You can
also use Secure Sockets Layer (SSL) or
• PowerShell scripts can be run on a schedule
Transport Layer Security (TLS) to encrypt the
using the Windows Task Scheduler. This allows
connection between the local and remote
you to automate tasks like backups, report
computers.
generation, and system maintenance without
manual intervention. • PowerShell Remoting allows you to manage
multiple remote computers simultaneously
• PowerShell scripts can be used to build more
using a single command. This makes it easy to
complex automation workflows by calling
perform common administrative tasks like
other scripts, functions, or cmdlets. This allows
software installation, patching, and
you to break down large tasks into smaller,
configuration changes across a large number of
more manageable pieces that can be reused
computers.
across different scripts and sessions.
• PowerShell Remoting can be configured to run
commands in the background, allowing you to
REMOTING
continue working on other tasks while the
PowerShell Remoting allows you to execute remote command executes. This is especially
PowerShell commands and scripts on remote useful for long-running tasks like software
computers. It enables you to manage large numbers installations or system backups.
of computers or servers from a single, centralized • PowerShell Remoting can be used in
location, without having to physically access each combination with other PowerShell features
one. like workflows and Desired State Configuration
(DSC) to build complex automation workflows
Here are some key things to know about
and ensure consistent configuration across
PowerShell Remoting:
large numbers of computers.
THE
THELANGUAGE
LANGUAGE cmdlet.
Operators are used to perform mathematical and In PowerShell, bitwise operators are used to
logical operations on values and variables. manipulate binary values at the bit level. Here are
the bitwise operators available in PowerShell:
Operators Description
Operator Description
+ addition
-bnot Flips all bits in the input
- subtraction
value
* multiplication
-bor Sets each bit in the
/ division result to 1 if either or
# Bitwise XOR
directory
If the condition is false, the code to execute in the
Get-ChildItem C:UsersPublic*.txt
else block is executed instead.
# Search for the word "error" in all You can also chain multiple conditions together
files with a ".log" extension in the using the elseif keyword:
C:WindowsLogs directory
Get-ChildItem C:WindowsLogs*.log |
if (condition1) {
Select-String "error"
# Code to execute if condition1
is true
# Filter all processes whose name
} elseif (condition2) {
begins with "w" using the -like
# Code to execute if condition2
operator
is true
Get-Process | Where-Object { $_.Name
} else {
-like "w*" }
# Code to execute if neither
condition1 nor condition2 is true
# Search for all strings in an array
}
that match a pattern using the
-match operator
$strings = "apple", "banana", You can also use the -and and -or operators to
"cherry" combine conditions together:
$strings -match "a"
if (condition) {
Here’s an example of using the ternary operator in
# Code to execute if condition
PowerShell:
Note that the ternary operator is useful for simple For Loop
comparisons and expressions, but can quickly
become unwieldy for more complex scenarios. In The For loop is a classic loop that allows you to
those cases, it’s better to use an if statement for iterate over a range of values a specific number of
clarity and readability. times.
ForEach Loop
Switch statements can also be used with regular
expressions or wildcards to match against patterns. The ForEach loop allows you to iterate over a
To use a regular expression, use the -regex collection of items, such as an array or a list.
parameter instead of -exact. To use a wildcard
pattern, use the -wildcard parameter instead of The basic syntax for a ForEach loop is as follows:
-exact.
collection in turn, and the code to execute for each would return the first item in the array.
item is enclosed in curly braces {}.
You can add items to an array using the += operator.
For example:
While Loop
$array += "new item"
The While loop allows you to repeatedly execute a
block of code while a certain condition is true.
would add the string "new item" to the end of the
array.
The basic syntax for a While loop is as follows:
Example:
while (condition) {
# Code to execute while # Create an array of strings
condition is true $colors = ("red", "green", "blue")
}
# Access individual items in the
The code to execute is enclosed in curly braces {}, array
and the condition is checked at the beginning of Write-Host $colors[0] # Output:
each iteration. red
• $i = 0 ; while ($i -lt 10) { Write-Host $i ; A hashtable is a collection of key-value pairs, where
$i++ } would output the numbers 0 through 9, each key is unique and maps to a specific value.
one per line.
In PowerShell, you can create a hashtable using the
@{} notation, with each key-value pair separated by
DATA STRUCTURES a semicolon ;.
# Access the value for a specific You can extract a slice of an array using the ..
key operator. Here’s an example:
Write-Host $ages["John"] #
Output: 30
$list = @(1, 2, 3, "four", "five")
# Add a new key-value pair $slice = $list[1..3] # returns
$ages["Bob"] = 40 the elements at index 1, 2, and 3
Write-Host $ages #
Output: {John=30; Jane=25; Bob=40}
Removing Elements from a List
JCG delivers over 1 million pages each month to more than 700K software
developers, architects and decision makers. JCG offers something for everyone,
including news, tutorials, cheatsheets, research guides, feature articles, source code
and more.
CHEATSHEET FEEDBACK
WELCOME
[email protected]
Copyright © 2014 Exelixis Media P.C. All rights reserved. No part of this publication may be SPONSORSHIP
reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, OPPORTUNITIES
mechanical, photocopying, or otherwise, without prior written permission of the publisher. [email protected]