PowerShell Study Notes
PowerShell Study Notes
Table of Contents
Introduction...................................................................................................... 3
UI...................................................................................................................... 3
Aliases.............................................................................................................. 3
Basic Commands.............................................................................................. 4
Get-Command............................................................................................... 4
Get-Help........................................................................................................ 4
Get-ChildItems.............................................................................................. 4
Set-Location.................................................................................................. 4
Clear-Host..................................................................................................... 4
Piping Commands............................................................................................ 5
Providers.......................................................................................................... 5
Variables.......................................................................................................... 6
Variable Types............................................................................................... 6
Comparisons................................................................................................. 7
Implicit Type Conversion...............................................................................7
Strings.............................................................................................................. 8
String Interpolation....................................................................................... 8
String Formatting.......................................................................................... 8
Wildcards...................................................................................................... 8
Arrays............................................................................................................... 9
Hash Tables...................................................................................................... 9
Common Built-in Variables............................................................................. 10
Branching....................................................................................................... 10
If Statement................................................................................................ 10
Switch Statement........................................................................................ 11
Looping.......................................................................................................... 11
Script Blocks................................................................................................... 12
Functions........................................................................................................ 13
Comments...................................................................................................... 13
Adding Help to Functions................................................................................ 13
Error Handling................................................................................................ 14
1
Introduction
DOS was a command-line based operating system. CMD lived on when
Windows replaced DOS. CMD was long overdue for replacement and
PowerShell does exactly that.
PowerShell is based .NET and everything is a .NET object.
Commands in PowerShell are named Cmdlets (Command-lets).
PowerShell commands have a Verb-Noun syntax.
Verbs like: Get, Set, Out, Start, Stop, Restart, Add.
Nouns like: Help, Command, Service, Computer, Location, ChildItems.
UI
Use can access PowerShell through:
Aliases
DOS and Linux commands work in PowerShell through Aliases.
PowerShell can accept aliases to its commands. For example these three
commands are the same:
Dir (DOS)
LS (Linux)
Get-ChildItems (PowerShell)
Basic Commands
Get-Command
Gets all the PowerShell commands.
Example:
Get-Command
Get-Command verb get
Get-Command noun service
Get-Help
Gets basic information about Cmdlets and other elements of PowerShell
commands.
Format: Get-Help <Command> -<Optional-Parameter>
Example:
Get-Help
Get-Help
Get-Help
Get-Help
Get-Command
Get-Command examples
Get-Command detailed
Get-Command full
Get-ChildItems
Lists sub items under the current location.
Example: Get-ChildItems
Set-Location
Changes the current path whether its a directory or tree of objects.
Format: Set-Location <New-Location>
Example:
Set-Location C:\Windows
Set-Location C:\Program Files
4
Clear-Host
Clears the screen.
Piping Commands
In PowerShell, Piping is the process of chaining commands so that the
output of the first command can be channeled as an input to the second
command whose output will be the input of the third command and so forth.
The name comes from the pipe symbol | (usually Shift + the key above the
left Enter) used to separate commands.
Example:
The pipe takes the output of the Get-ChildItems and passes it to the
Where-Object command which prints out the result of files that have length
greater than 100 KB.
When writing piped commands on multiple lines you have to end each line
with the pipe symbol (except the last line which ends with the last command).
Providers
PowerShell uses providers which provide access to data and components that
would not otherwise be easily accessible at the command line. The data
is presented in a consistent format that resembles a file system drive
(Source).
To list PowerShell providers use: Get-PSProvider
We connect to PowerShell Providers by mounting the Providers PowerShell
Drive (PSDrive). Most Providers have only one PSDrive, the exceptions are the
FileSystem Provider (depends on the number of drives on the system) and the
Registry Provider (HKLM and HKCU) (Source).
To list PowerShell drives use: Get-PSDrive
To move/switch to a certain drive use: Set-Location <PSDrive>:
Example: Set-Location Env:
To get a list of currently loaded Snap-ins use: Get-PSSnapIn
To get a list of Snap-ins that are registered but not currently loaded use: GetPSSnapIn -Registered
5
Variables
To create a variable just put a dollar sign ($) before the name of the variable
and assign a value to it.
Example: $hi = Hello World
This is a shortcut for using the New-Variable cmdlet. You can use the long
form.
Example: New-Variable Name hi Value Hello World
To assign a value to an existing variable, use the Set-Variable cmdlet.
Example: Set-Variable Name hi Value 5
To print out a variables value, just write the name of the variable after a
dollar sign.
Example: $hi
To clear the content of a variable (like setting it to Null), use the ClearVariable cmdlet.
Example: Clear-Variable Name hi
This is a shortcut for using the Write-Host cmdlet. You can use the long
form.
Example: Write-Host $hi
Its also a shortcut for using the Get-Variable cmdlet. You can use the long
form.
Example: Get-Variable hi valueonly
The cmdlet Get-Variable (without any parameters) will list all the variables
in PowerShell.
To remove a variable from memory, use the Remove-Variable cmdlet.
Example: Remove-Variable Name hi
6
Variable Types
To Get type of a variable use: <Variable-Name>.GetType()
Example: $hi.GetType()
PowerShell types are mutable. Assigning an integer value to a variable
holding a string will change the type of the variable from string to integer.
You can declare a variable and assign a specific type to it. This will cause
PowerShell to throw an error if you assign a wrong type of value to it.
To declare the type of a variable, write the .NET full name of the type before
the variable name in square brackets.
Example: [System.Int32]$myint = 42
Comparisons
PowerShell doesnt use symbols for comparisons. Instead it uses short
acronyms following a dash.
Greater Than
Less Than
Equal To
Not Equal To
Greater Than or Equal
Less Than or Equal
Like
Not Like
Match based on regular expressions
Non-match
based
on
regular
expresions
Calculations are like any other language. You
-gt
-lt
-eq
-ne
-ge
-le
-like
-NotLike
-Match
-NonMatch
can use +, -, ++, -- and /
Strings
You can single quotes or double quotes around strings.
The escape character in PowerShell is the backtick (left to the 1 key and
below the Esc key).
Some escape sequences:
Backspace
`b
New Line
`n
Carriage Return
`r
Carriage Return Line Feed
`r`n
Tab
`t
A Here String is a way of writing text on multiple lines. Use (@) before the
lines of text and (@) after the text. Make sure that each symbol is on its own
line and is not mixed with the text.
Correct
$heretext = @
Some text here
More text here
Incorrect
$heretext = @
Some text here
More text here
String Interpolation
PowerShell can replace variables with their values when printing out strings.
8
String Formatting
You can format strings just like you do in .NET using the String.Format
method.
Example: [string]::Format(There are {0} items., $items)
Or using the PowerShell shortcut
Example: There are {0} items. f $items
Wildcards
Here are some wildcards to be used with the like and match string
comparisons:
*
?
*[a-z]
*[c-g]
*[1-9]
*[4-8]
[4-8]
{2}
[c-g]{3}
a to z
c to g
1 to 9
4 to 8
Arrays
To assign an array, simple list all the values separated by a comma.
Example: $array = value1, value2
Arrays are zero-based. To access the first value, use the index zero.
Example: $array[0]
To create an empty array, use the following syntax:
$array = @()
This syntax can also be used to create an array:
$array = @(value1, value2)
You can create an array of numeric range with this shortcut:
9
Hash Tables
Hash tables are the PowerShell equivalent of .NET dictionaries.
To create a hash table, use this syntax:
$hashtable = @{Key1 = Value1; Key2 = Value2; key3 = value3}
To get a single value, use a syntax similar to getting a value from an array:
$hashtable[Key1]
Or you can use this: $hashtable.Key1
The value Key1 can be replaced by a variable or expression which will be
evaluated and replaced with the correct value before getting the key value
from the hash table.
To remove a key from table, use $<TableName>.Remove(<KeyName>)
Example: $hashtable.Remove(Key1)
You can search in keys or values:
Example:
True value
False value
Current directory
Users home directory
Info about the users machine
Process ID
Branching
If Statement
If statements are very similar to those in .NET (C# to be specific) except it
doesnt support Else if. Heres an example:
If ($hi eq Hello)
{
It equals Hello
}
Else
{
If ($hi eq Hi)
{
It equals Hi
}
Else
{
Its something else
}
}
Switch Statement
Also simple:
Switch ($hi)
{
Hello { Its Hello; break }
Hi { Its hi; break }
Default { Something else }
}
Make sure to break to skip matching the next values in the list, otherwise it
will continue down the list which is a waste of time.
Looping
You can loop using multiple commands including the While command:
$i = 1
While ($i le 5)
{
`$i = $i
$i = $i + 1
}
11
Script Blocks
A script block is the code inside curly brackets.
To put multiple commands on a single line user the semi-colon to separate
them.
Writing a script block on its own will not execute it, but will just print it out.
{Clear-Host; Hello World}
To execute a script block, you need to add & before the script block.
& {Clear-Host; Hello World}
You can store a script block in a variable
$script = {Clear-Host; Hello World}
12
Functions
A function is a script block with a name.
Function Get-Total ($n1, $n2)
{
Write-Host ($n1 + $n2)
}
Variables are passed to functions by value (ByVal in .NET). You can pass
variables by reference using this syntax:
Function Get-Total([ref] $n1, [ref] $n2)
13
Comments
To add a comments block in PowerShell, start with <# and end with #>.
Error Handling
To catch errors in a function, use the keyword Trap at the end of the function
and execute a script block that handles the error.
Example:
Function FuncWithError()
{
<# Do something here that might throw an error #>
Trap
{
Write-Host An error occurred
Write-Host $_.ErrorID
Write-Host $_.Exception.Message
14
15