PowerShell Reference
(Updated: 2019-09-04) - 
Highlights - 
Concepts - 
Resources - 
Names - 
Aliases - 
Getting Help - 
Using Variables - 
Pipeline - 
Remoting
Highlights
PowerShell Variables
Creating and working with variables is simple. To create a variable, prefix the variable name with the $ and then give the variable a value:
$loc = Get-Location
To call the variable, you need only type in the $ and the variable name:
$loc
PowerShell Comparison Operators
Comparison operators typically return a true or a false. Here are the common comparison operators in use with PowerShell:
  
    | Operator | Description | 
    | -gt or -ge | Greater than or greater than or equal to. | 
    | -lt or -le | Less than or less than or equal to. | 
    | -eq or -ne | Equal to or not equal to. | 
    | -and | If both inputs are true, then the output is true. | 
    | -or | If one of the inputs is true, then the output is true. | 
    | -like or -notlike | Uses a wildcard to match patterns. | 
    
| -contains and -notcontains | Checks to see if a particular value exists in an array. | 
  
PowerShell Loops and Conditionals
Conditionals are great when you need to evaluate input based on a certain set of criteria and execute a specific block of code based on that evaluation. One of the most common types is the If statement.
$car = 'Nissan'
If ($car -eq 'Ford') {
Write-Host 'This is a Ford car.'
}
ElseIf ($car -eq 'Chevrolet') {
Write-Host 'This is a Chevrolet car.'
}
ElseIf ($car -eq 'Nissan') {
Write-Host 'This is a Nissan car.'
Else {
Write-Host "Don't know what kind of car this is."
}
Loops are useful when you want to use the same action against multiple objects. Here are some examples of types of loops.
ForEach
ForEach is used to enumerate a set of data. In the following example, the ForEach is being used to go through all the processes returned from Get-Process and it returns their names.
foreach ($proc in Get-Process){Write-Host $proc.name}
While
Initializes the $num variable with 1 and increments by one with each loop as long as the number is less than or equal to 10. Prints the value of $num with each loop.
$num = 1
while ($num -le 10) {
Write-Host $num
$num ++
}
Do . . . While
Initializes the $myint variable with 1, and then increments the value of $myint by 1 through each loop until $myint is no longer less than or equal to 5. Prints the value of $myint through each loop.
$myint = 1
do
{
"Starting loop number $myint"
$myint
$myint++
"Now my integer is $myint"
} While ($myint -le 5)
PowerShell Aliases
Aliases are shortcuts for some of the more common commands. You can use an alias much as you would the full command. For example, the following two commands will do the same thing. One is using the alias; the other is not.
Get-Process | Format-Table
Get-Process | ft
Here are some of the most frequently used aliases:
  | Alias | Full Command | 
  | gcm | Get-Command | 
  | sort | Sort-Object | 
  | gi | Get-Item | 
  | cp | Copy-Item | 
  
| fl | Format-List | 
  | ft | Format-Table | 
  | pwd | Get-Location | 
  | cls | Clear-Host | 
  | ni | New-Item | 
  
| sleep | Start-Sleep | 
  | write | Write-Output | 
  | where | Where-Object | 
 
How to Run PowerShell Scripts
To create and run a PowerShell script, follow these steps:
  - Create your PowerShell script and save it as a PS1 file.
 This is the PowerShell file extension.
- Open a PowerShell window by right-clicking Start and then choosing Windows PowerShell (Admin).
- Navigate to the directory the script is located in and then type the following to execute the script from the current directory:
 .\yourscript.ps1
If you get an error when you try to run your script, it may be due to your execution policy being set too restrictive. Try running the following:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
How to Access PowerShell Help
It’s always useful to know how to get help in PowerShell if you get stuck on the proper usage of a command. Here are helpful ways to get some assistance on the command line.
To update the help files on your system, run this cmdlet:
Update-Help
Running the following command will display the basic help file for the Get-Process command, including a description and the appropriate syntax. You can run Get-Help for any cmdlet, not just Get-Process.
Get-Help Get-Process
Running the command with the -Detailed parameter will give you additional information like descriptions of the parameters and examples of how to use the cmdlet.
Get-Help Get-Process -Detailed
Running the command with the -Full parameter will give you additional information like descriptions of the parameters and examples of how to use the cmdlet, as well as the types of input/output objects and any additional notes that might appear in the help file.
Get-Help Get-Process -Full
The last cmdlet you should know is the Get-Member cmdlet. If you aren’t sure how to interact with a cmdlet, Get-Member can give you the methods and the properties associated with the cmdlet.
Get-Process | Get-Member
Basics
  | Cmdlet | Commands built into shell written in .NET | 
  | Functions | Commands written in PowerShell language | 
  | Parameter | Argument to a Cmdlet/Function/Script | 
  | Alias | Shortcut for a Cmdlet or Function | 
  | Scripts | Text files with .ps1 extension | 
  | Applications | Existing windows programs | 
  | Pipelines | | Pass objects Get-process word | Stop-Process | 
  | Ctrl+c | Interrupt current command | 
  | Left/right | Navigate editing cursor | 
  | Ctrl+left/right | Navigate a word at a time | 
  | Home / End | Move to start / end of line | 
  | Up/down | Move up and down through history | 
  | Insert | Toggles between insert/overwrite mode | 
  | F7 | Command history in a window | 
  | Tab / Shift-Tab | Command line completion | 
Writing output and reading input
  | "This displays a string" | String is written directly to output | 
  | Write-Host "color" -ForegroundColor Red -NoNewLine | String with colors, no new line at end | 
  | $age = Read-host "Please enter your age" | Set $age variable to input from user | 
  | $pwd = Read-host "Please enter your password" -asSecure | StringRead in $pwd as secure string | 
  | Clear-HostClear | console | 
Top - 
Home
 
Concepts
Output is object-based
Unlike traditional command-line interfaces, PowerShell cmdlets are designed to deal with objects.
An object is structured information that is more than just the string of characters appearing on the
screen. Command output always carries extra information that you can use if you need it.
The command family is extensible
The native commands in PowerShell are known as cmdlets (pronounced command-lets). You can create
your own cmdlets modules and functions using compiled code or scripts. Modules can add cmdlets and
providers to the shell. PowerShell also supports scripts that are analogous to UNIX shell scripts
and cmd.exe batch files.
When you type a command, PowerShell always processes the command-line input directly. PowerShell
also formats the output that you see on the screen. This difference is significant because it
reduces the work required of each cmdlet. It ensures that you can always do things the same way
with any cmdlet. Cmdlet developers don't need to write code to parse the command-line arguments or
format the output.
Note
If you run a graphic application in PowerShell, the window for the application opens.
PowerShell intervenes only when processing the command-line input you supply or the application
output returned to the console window. It does not affect how the application works internally.
PowerShell uses some C# syntax
PowerShell is built on the .NET Framework. It shares some syntax features and keywords with the C#
programming language. Learning PowerShell can make it much easier to learn C#. If you're already
familiar with C#, these similarities can make learning PowerShell easier.
Top - 
Home
 
Resources
Other sources to learn PowerShell
Resources for PowerShell users
In addition to the Help available at the command line, the following resources provide more
information for users who want to run PowerShell.
  - PowerShell Team Blog. The best resource for learning
directly from the PowerShell product team.
- The Hey, Scripting Guy! Blog articles are
scenario-driven, and written in an engaging and lively manner.
- Have questions about using PowerShell? Connect with hundreds of other people who have similar
interests in one of the many community forums listed on the PowerShell Community
page.
Channel 9 videos
Channel 9 is our video publishing platform. There are hundreds of videos about PowerShell
available. Search for "PowerShell"
to see what videos are available.
Microsoft Virtual Academy
The Microsoft Virtual Academy videos have been moved to Channel 9.
Top - 
Home
 
Names
Learning command names in traditional shells
Most commands are built to manage elements of the operating system or applications, such as
services or processes. The commands have names that may or may not fit into a family. For example,
on Windows systems, you can use the net start and net stop commands to start and stop a
service. Sc.exe is another service control tool for Windows. That name does not fit into the
naming pattern for the net.exe service commands. For process management, Windows has the
tasklist.exe command to list processes and the taskkill.exe command to kill processes.
Also, these commands have irregular parameter specifications. You can't use the net start command
to start a service on a remote computer. The sc.exe command can start a service on a remote
computer. But to specify the remote computer, you must prefix its name with a double backslash. To
start the spooler service on a remote computer named DC01, you type sc.exe \\DC01 start spooler.
To list tasks running on DC01, you use the /S parameter and the computer name without
backslashes. For example, tasklist /S DC01.
Note
Prior to PowerShell v6, sc was an alias for the Set-Content cmdlet. Therefore, to run
the sc.exe command in a version of PowerShell prior to v6, you must include the
full filename sc.exe including the file extension exe.
Services and processes are examples of manageable elements on a computer that have well-defined
life cycles. You may start or stop services and processes, or get a list of all currently
running services or processes. Although there are important technical distinctions between them,
the actions you perform on services and processes are conceptually the same. Furthermore, the
choices we make to customize an action by specifying parameters may be conceptually similar as
well.
PowerShell exploits these similarities to reduce the number of distinct names you need to know to
understand and use cmdlets.
Cmdlets use verb-noun names to reduce command memorization
PowerShell uses a "verb-noun" naming system. Each cmdlet name consists of a standard verb
hyphenated with a specific noun. PowerShell verbs are not always English verbs, but they express
specific actions in PowerShell. Nouns are very much like nouns in any language. They describe
specific types of objects that are important in system administration. It's easy to demonstrate
how these two-part names reduce learning effort by looking at a few examples.
PowerShell has a recommended set of standard verbs. Nouns are less restricted, but always describe
what the verb acts upon. PowerShell has commands such as Get-Process, Stop-Process,
Get-Service, and Stop-Service.
It's easy to understand what a PowerShell command does by reading its name. The command to shut
down a computer is Stop-Computer. The command to list all computers on a network is
Get-Computer. The command to get the system date is Get-Date.
You can list all commands that include a particular verb with the Verb parameter for
Get-Command. For example, to see all cmdlets that use the verb Get, type:
PS> Get-Command -Verb Get
CommandType     Name                            Definition
-----------     ----                            ----------
Cmdlet          Get-Acl                         Get-Acl [[-Path] <String[]>]...
Cmdlet          Get-Alias                       Get-Alias [[-Name] <String[]...
Cmdlet          Get-AuthenticodeSignature       Get-AuthenticodeSignature [-...
Cmdlet          Get-ChildItem                   Get-ChildItem [[-Path] <Stri...
...
Use the Noun parameter to see a family of commands that affect the same type of object. For
example, run following command to see the commands  available for managing services:
PS> Get-Command -Noun Service
CommandType     Name                            Definition
-----------     ----                            ----------
Cmdlet          Get-Service                     Get-Service [[-Name] <String...
Cmdlet          New-Service                     New-Service [-Name] <String>...
Cmdlet          Restart-Service                 Restart-Service [-Name] <Str...
Cmdlet          Resume-Service                  Resume-Service [-Name] <Stri...
Cmdlet          Set-Service                     Set-Service [-Name] <String>...
Cmdlet          Start-Service                   Start-Service [-Name] <Strin...
Cmdlet          Stop-Service                    Stop-Service [-Name] <String...
Cmdlet          Suspend-Service                 Suspend-Service [-Name] <Str...
...
The Help parameter (?)
When you specify the -? parameter on any cmdlet, PowerShell displays help for the cmdlet.
The cmdlet is not executed.
Common parameters
PowerShell has several common parameters. These parameters are controlled by the PowerShell
engine. Common parameters always behave the same way. The common parameters are WhatIf,
Confirm, Verbose, Debug, Warn, ErrorAction, ErrorVariable, OutVariable,
and OutBuffer.
Recommended parameter names
The PowerShell core cmdlets use standard names for similar parameters. The use of these standard
names is not enforced, but there is explicit guidance to encourage standardization.
For example, the recommended name for a parameter that refers to a computer is ComputerName,
rather than Server, Host, System, Node, or some other common alternative. Other important
recommended parameter names are Force, Exclude, Include, PassThru, Path, and
CaseSensitive.
Top - 
Home
 
Aliases
PowerShell supports aliases to refer to commands by alternate names. Aliasing allows users with
experience in other shells to use common command names that they already know for similar
operations in PowerShell.
If you have used cmd.exe for years, you might reflexively type the cls command
to clear the screen. Without the alias for Clear-Host, you receive an error message and won't
know what to do to clear the output.
The following list shows a few of the common cmd.exe and Unix commands that you can use in
PowerShell:
  | cat | dir | mount | rm | 
  | cd | echo | move | rmdir | 
  | chdir | erase | popd | sleep | 
  | clear | h | ps | sort | 
  | cls | history | pushd | tee | 
  | copy | kill | pwd | type | 
  | del | lp | r | write | 
  | diff | ls | ren |  | 
The Get-Alias cmdlet shows you the real name of the native PowerShell command associated with an
alias.
PS> Get-Alias cls
CommandType     Name                               Version    Source
-----------     ----                               -------    ------
Alias           cls -> Clear-Host
Creating new aliases
You can create your own aliases using the Set-Alias cmdlet. For example, the following statements
create the standard cmdlet aliases previously discussed:
Set-Alias -Name gi -Value Get-Item
Set-Alias -Name si -Value Set-Item
Set-Alias -Name gl -Value Get-Location
Set-Alias -Name sl -Value Set-Location
Set-Alias -Name gcm -Value Get-Command
Top - 
Home
 
Getting Help
PowerShell includes detailed Help articles that explain PowerShell concepts and the PowerShell
language. There are also Help articles for each cmdlet and provider and for many functions and
scripts.
To get Help about PowerShell cmdlets, use the
Get-Help cmdlet. For example, to get Help
for the Get-ChildItem cmdlet, type:
Get-Help Get-ChildItem
or
Get-ChildItem -?
To get a list of all the cmdlet Help articles in your session, type:
Get-Help -Category Cmdlet
To display one page of each Help article at a time, use the help function or its alias man.
For example, to display Help for the Get-ChildItem cmdlet, type
man Get-ChildItem
or
help Get-ChildItem
To display detailed information, use the Detailed parameter of the Get-Help cmdlet. For
example, to get detailed information about the Get-ChildItem cmdlet, type:
Get-Help Get-ChildItem -Detailed
To display all content in the Help article, use the Full parameter of the Get-Help cmdlet. For
example, to display all content in the Help article for the Get-ChildItem cmdlet, type:
Get-Help Get-ChildItem -Full
To display only the examples in a Help article, use the Examples parameter of the Get-Help.
For example, to display only the examples in the Help article for the Get-ChildItem cmdlet, type:
Get-Help Get-ChildItem -Examples
Top - 
Home
 
Using Variables
PowerShell works with objects. PowerShell lets you create named objects known as variables.
Variable names can include the underscore character and any alphanumeric characters. When used in
PowerShell, a variable is always specified using the $ character followed by variable name.
Creating a variable
You can create a variable by typing a valid variable name:
PS> $loc
PS>
This example returns no result because $loc doesn't have a value. You can create a variable and
assign it a value in the same step. PowerShell only creates the variable if it doesn't exist.
Otherwise, it assigns the specified value to the existing variable. The following example stores
the current location in the variable $loc:
$loc = Get-Location
PowerShell displays no output when you type this command. PowerShell sends the output of
'Get-Location' to $loc. In PowerShell, data that isn't assigned or redirected is sent to the
screen. Typing $loc shows your current location:
PS> $loc
Path
----
C:\temp
You can use Get-Member to display information about the contents of variables. Get-Member shows
you that $loc is a PathInfo object, just like the output from Get-Location:
PS> $loc | Get-Member -MemberType Property
   TypeName: System.Management.Automation.PathInfo
Name         MemberType Definition
----         ---------- ----------
Drive        Property   System.Management.Automation.PSDriveInfo Drive {get;}
Path         Property   System.String Path {get;}
Provider     Property   System.Management.Automation.ProviderInfo Provider {...
ProviderPath Property   System.String ProviderPath {get;}
Manipulating variables
PowerShell provides several commands to manipulate variables. You can see a complete listing in a
readable form by typing:
Get-Command -Noun Variable | Format-Table -Property Name,Definition -AutoSize -Wrap
PowerShell also creates several system-defined variables. You can use the Remove-Variable cmdlet
to remove variables, which are not controlled by PowerShell, from the current session. Type the
following command to clear all variables:
Remove-Variable -Name * -Force -ErrorAction SilentlyContinue
After running the previous command, the Get-Variable cmdlet shows the PowerShell system variables.
PowerShell also creates a variable drive. Use the following example to display all PowerShell
variables using the variable drive:
Get-ChildItem variable:
Using cmd.exe variables
PowerShell can use the same environment variables available to any Windows process, including
cmd.exe. These variables are exposed through a drive named env:. You can view these
variables by typing the following command:
Get-ChildItem env:
The standard *-Variable cmdlets aren't designed to work with environment variables. Environment
variables are accessed using the env: drive prefix. For example, the %SystemRoot% variable in
cmd.exe contains the operating system's root directory name. In PowerShell, you use
$env:SystemRoot to access the same value.
PS> $env:SystemRoot
C:\WINDOWS
You can also create and modify environment variables from within PowerShell. Environment variables
in PowerShell follow the same rules for environment variables used elsewhere in the operating
system. The following example creates a new environment variable:
$env:LIB_PATH='/usr/local/lib'
Though not required, it's common for environment variable names to use all uppercase letters.
Top - 
Home
 
Pipeline
Pipelines act like a series of connected segments of pipe. Items moving along the pipeline pass
through each segment. To create a pipeline in PowerShell, you connect commands together
with the pipe operator "|". The output of each command is used as input to the next command.
The notation used for pipelines is similar to the notation used in other shells. At first glance, it
may not be apparent how pipelines are different in PowerShell. Although you see text on the screen,
PowerShell pipes objects, not text, between commands.
The PowerShell pipeline
Pipelines are arguably the most valuable concept used in command-line interfaces. When used
properly, pipelines reduce the effort of using complex commands and make it easier to see the flow
of work for the commands. Each command in a pipeline (called a pipeline element) passes its output
to the next command in the pipeline, item-by-item. Commands don't have to handle more than one item
at a time. The result is reduced resource consumption and the ability to begin getting the output
immediately.
Objects in the pipeline
When you run a cmdlet in PowerShell, you see text output because it is necessary to represent
objects as text in a console window. The text output may not display all of the properties of the object being output.
For example, consider the Get-Location cmdlet. If you run Get-Location while
your current location is the root of the C drive, you see the following output:
PS> Get-Location
Path
----
C:\
The text output is a summary of information, not a complete representation of the object returned
by Get-Location. The heading in the output is added by the process that formats the data for
onscreen display.
When you pipe the output to the Get-Member cmdlet you get information about the object returned by
Get-Location.
Get-Location | Get-Member
TypeName: System.Management.Automation.PathInfo
Name         MemberType Definition
----         ---------- ----------
Equals       Method     bool Equals(System.Object obj)
GetHashCode  Method     int GetHashCode()
GetType      Method     type GetType()
ToString     Method     string ToString()
Drive        Property   System.Management.Automation.PSDriveInfo Drive {get;}
Path         Property   string Path {get;}
Provider     Property   System.Management.Automation.ProviderInfo Provider {get;}
ProviderPath Property   string ProviderPath {get;}
Get-Location returns a PathInfo object that contains the current path and other information.
Top - Home
 
Remote
You can run commands on one or hundreds of computers with a single PowerShell command. Windows
PowerShell supports remote computing by using various technologies, including WMI, RPC, and
WS-Management.
PowerShell Core supports WMI, WS-Management, and SSH remoting. RPC is no longer supported.
For more information about remoting in PowerShell Core, see the following articles:
- SSH Remoting in PowerShell Core
- WSMan Remoting in PowerShell Core
Windows PowerShell Remoting Without Configuration
Many Windows PowerShell cmdlets have the ComputerName parameter that enables you to collect data
and change settings on one or more remote computers. These cmdlets use varying communication
protocols and work on all Windows operating systems without any special configuration.
These cmdlets include:
- Restart-Computer
- Test-Connection
- Clear-EventLog
- Get-EventLog
- Get-HotFix
- Get-Process
- Get-Service
- Set-Service
- Get-WinEvent
- Get-WmiObject
Typically, cmdlets that support remoting without special configuration have the ComputerName parameter and don't have the Session parameter. To find these cmdlets in your session, type:
Get-Command | where { $_.parameters.keys -contains "ComputerName" -and $_.parameters.keys -notcontains "Session"}
Windows PowerShell Remoting
Using the WS-Management protocol, Windows PowerShell remoting lets you run any Windows
PowerShell command on one or more remote computers. You can establish persistent connections,
start interactive sessions, and run scripts on remote computers.
Start an Interactive Session
To start an interactive session with a single remote computer, use the
Enter-PSSession cmdlet.
For example, to start an interactive session with the Server01 remote computer, type:
Enter-PSSession Server01
The command prompt changes to display the name of the remote computer. Any commands that you type
at the prompt run on the remote computer and the results are displayed on the local computer.
To end the interactive session, type:
Exit-PSSession
Run a Remote Command
To run a command on one or more computers, use the Invoke-Command cmdlet. For example, to run a Get-UICulturecommand on the Server01 and Server02 remote computers, type:
Invoke-Command -ComputerName Server01, Server02 -ScriptBlock {Get-UICulture}
The output is returned to your computer.
LCID    Name     DisplayName               PSComputerName
----    ----     -----------               --------------
1033    en-US    English (United States)   server01.corp.fabrikam.com
1033    en-US    English (United States)   server02.corp.fabrikam.com
Run a Script
To run a script on one or many remote computers, use the FilePath parameter of the Invoke-Command
cmdlet. The script must be on or accessible to your local computer. The results are returned to
your local computer.
For example, the following command runs the DiskCollect.ps1 script on the remote computers,
Server01 and Server02.
Invoke-Command -ComputerName Server01, Server02 -FilePath c:\Scripts\DiskCollect.ps1
Establish a Persistent Connection
Use the New-PSSession cmdlet to create a persistent session on a remote computer. The following
example creates remote sessions on Server01 and Server02. The session objects are stored in the
$s variable.
$s = New-PSSession -ComputerName Server01, Server02
Now that the sessions are established, you can run any command in them. And because the sessions
are persistent, you can collect data from one command and use it in another command.
For example, the following command runs a Get-HotFix command in the sessions in the $s variable and
it saves the results in the $h variable. The $h variable is created in each of the sessions in $s,
but it doesn't exist in the local session.
Invoke-Command -Session $s {$h = Get-HotFix}
Now you can use the data in the $h variable with other commands in the same session. The results
are displayed on the local computer. For example:
Invoke-Command -Session $s {$h | where {$_.InstalledBy -ne "NTAUTHORITY\SYSTEM"}}
Advanced Remoting
Windows PowerShell remote management just begins here. By using the cmdlets installed with Windows
PowerShell, you can establish and configure remote sessions both from the local and remote ends,
create customized and restricted sessions, allow users to import commands from a remote session
that actually run implicitly on the remote session, configure the security of a remote session, and
much more.
Windows PowerShell includes a WSMan provider. The provider creates a WSMAN: drive that lets you
navigate through a hierarchy of configuration settings on the local computer and remote computers.
For more information about the WSMan provider, see
WSMan Provider or in the Windows PowerShell console, type Get-Help wsman.
For more information, see:
For help with remoting errors, see about_Remote_Troubleshooting.
See Also
Top - 
Home