Scripting >> Powershell >> 5.1 >> Powershell 5.1 Cheatsheet

 

Work in progress ....

 

Jump to: Help | Automatic Variables | Common parameters | Commands | Pipeline | Functions | Scripts | Objects | Operators | Providers | Variables & Data Types | Arrays | Hashtables/Ordered Dictionary | Flow Control (Loop, Branch) | Scope | Modules | Output Formatting | Date & Time | Strings | Files & Directories | Language Reference | Working with (MS Word, Excel) |

 

Reserved Words  

assembly class do enum foreach inlinescript param sequence try workflow
base command dynamicparam exit function interface private static type  
begin configuration else filter hidden module process switch until  
break continue elseif finally if namespace public throw using  
catch data end for in parallel return trap while  

 

Help System  

Get-Help
:: Describes how to use the help system

 

PS C:\> get-help

TOPIC
    Windows PowerShell Help System

.....

Get-Help [<cmdlet>|keyword|keywordpattern]
or
Help <cmdlet>

PS C:\> get-help get-process
PS C:\> get-help about_If
PS C:\> get-help about_*

Go Top

Get-Command -Name <cmdlet> -Syntax

 

Get-Command -Name *user*
:: search for commands that contain the pattern user

 

Get-Command -Verb Get
:: list commands that start with verb Get

 

Get-Command -Noun Service
:: list commands that end with noun Service

PS C:\> get-command -name get-process -syntax

Get-Process [[-Name] <string[]>] [-ComputerName <string[]>] [-Module] [-FileVersionI
nfo] [<CommonParameters>]

Get-Process [[-Name] <string[]>] -IncludeUserName [<CommonParameters>]

Get-Process -Id <int[]> -IncludeUserName [<CommonParameters>]

Get-Process -Id <int[]> [-ComputerName <string[]>] [-Module] [-FileVersionInfo] [<Co
mmonParameters>]

Get-Process -InputObject <Process[]> -IncludeUserName [<CommonParameters>]

Get-Process -InputObject <Process[]> [-ComputerName <string[]>] [-Module] [-FileVers
ionInfo] [<CommonParameters>]

 Go Top

Common Parameters  
 -Debug (db) Displays programmer level detail
 -ErrorAction (ea) Determines how cmdlet responds to errors
 -ErrorVariable (ev) Stores error messages in a specified variable
 -OutVariable (ov) Stores output  in a specified variable
 -OutBuffer (ob) Determines number of output objects to accumulate in a buffer
 -PipelineVariable (pv) Stores value of current pipeline element as a variable
 -Verbose (vb) Displays detailed information
 -WarningAction (wa) Determines how cmdlet responds to warnings
 -WarningVariable (wv)

Stores warnings in a specified variable

Go Top

 

Commands  Examples
Discover all available commands

get-command

or it's alias

gcm

# will output all powershell cmdlets as well as
# external Windows commands (*.exe, *.bat etc that are in the current PATH)

Go Top


Pipeline  

Pipeline Output Formatting

Format-List

- Lists all available properties
- can customize with -Property parameter

 

Format-Table

- Display properties in a table
- properties as columns
- can customize with -Property, -AutoSize -GroupBy & -Wrap

Format-Wide

- Display in wide format, default 2 columns
- Shows only 1 property, default is Name
- Can customize number of columns with -Column paramter

 

 

eg.1
PS C:\temp> get-process | format-list


eg.2
PS C:\temp> get-process | format-list  -Property Name,Id


eg. 3
PS C:\temp> get-process | format-table


 

 Go Top

Functions
 

function <name>
{
    <statement list>
}

or

function <name>
{
    param (
        [type] $var1 [= <var1-default-value>],
        [type] $var2 [= <var2-default-value>] ...
    )
    <statement list>
}

or

function <name>
{
    [CmdletBinding(SupportsShouldProcess=$True)]
    Param (
        [type] $var1 [= <var1-default-value>],
        [type] $var2 [= <var2-default-value>] ...
    )
    Begin {
        # optional one-time preprocessing

        # for the function
    }
   
    Process {
        # provide record-by-record processing for
        # the function.        
        # can use a Process block without defining
        # Begin/End blocks.

    }
    End {
        # optional one-time post-processing
        # for the function
    }
}

eg. 1 - without parameters

function Get-ServiceInfo
{
Get-Service -Name spooler -ComputerName MyServer
}

eg. 2 - with parameters

function Get-ServiceInfo
{
param ($svc,$computer)
Get-Service -Name $svc -ComputerName $computer
}

 

 

 

 

 

 

 

 

 

 

 

 

Go Top

Scripts  
  • Reusable code
  • text file (.ps1) containing one or more powershell commands
  • can be digitaly signed

Can pass named parameters to the script

script.ps1
param (
type] $var1 = <var1-default-value> ,
[type] $var2 = <var2-default-value>
)
<statements>

run the script with parameters as follows

script.ps1 -var1 "var1value" -var2 "var2value"

for multi word string values enclose in with single quote '

script.ps1 -var1 "var1value" -var2 'multi word value'

for words containing special char like &
enclose the char with double quotes "

script.ps1 -var1 "var1value" -var2 "multi "&" word'

 

 

 

 

 

 

 

 

 

 

 

 

 

Go Top

Depends on ExecutionPolicy in effect

Restricted

  • Default
  • Scripts cannot be run
  • Powershell interactive mode only

AllSigned

  • Runs signed script only
  • signature must be trusted by local machine

RemoteSigned

  • runs all local scripts
  • downloaded scripts must be signed by trusted source

Unrestricted

  • run all scripts from all sources

> get-executionpolicy

> set-executionpolicy -ExecutionPolicy Restricted

> set-executionpolicy -ExecutionPolicy AllSigned

> set-executionpolicy -ExecutionPolicy RemoteSigned

> set-executionpolicy -ExecutionPolicy UnRestricted

require elevated privilege (run as administrator)

 

 

 

 

 

Go Top

Objects  

Get-Member [[-Name] <String[]>] [-InputObject <PSObject>] [-MemberType <PSMemberTypes>] [-View <PSMem
berViewTypes>] [-Static] [-Force] [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-WarningActi
on <ActionPreference>] [-ErrorVariable <String>] [-WarningVariable <String>] [-OutVariable <String>]
[-OutBuffer <Int32>]

 | Get-Member - send output pipeline to Get-Member to display the objects properties

e.g.

get-service -name spooler | get-member


Compare-Object [-ReferenceObject] <PSObject[]> [-DifferenceObject] <PSObject[]> [-SyncWindow <Int32>]
 [-Property <Object[]>] [-ExcludeDifferent] [-IncludeEqual] [-PassThru] [-Culture <String>] [-CaseSen
sitive] [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-WarningAction <ActionPreference>] [-E
rrorVariable <String>] [-WarningVariable <String>] [-OutVariable <String>] [-OutBuffer <Int32>]

e.g. 1 use it to compare content of 2 text files
$ref = get-content c:\temp\A.txt
$diff = get-content c:\temp\B.txt
Compare-Object -ReferenceObject $ref -DifferenceObject $diff

 

 

Go Top

Operators  

Arithmetic Operators

      +           Add

      -           Subtract

      *           Multiply

      /           Divide

      %           Modulus (remainder of)


Note for exponetiation, use [Math]::Pow(x, y) for x raise to the power of y.


 

 

Comparison operators

      -eq           Equal

      -ne          
Not equal

      -gt           Greater than

      -ge           Greater than or equal

      -lt           Less than

      -le           Less than or equal

      -Like         positive wildcard match

      -NotLike      negative wildcard match

      -Match        positive Regex match

      -NotMatch     negative Regex match

      -Contains     scalar (on the right)
                    is a member of the list (on the left)


      -NotContains  scalar (on the right)
                    not member of a list (on the left)


      -In           TRUE when test value matches
                    at least one of the reference values


      -NotIn       
TRUE when test value does not match
                    any of the reference values


      -Replace     
Changes the specified elements of a
                    value

 

Example : -eq
> 1+1 -eq 2
True

Example : -ne
> 1+1 -ne 3
True

Example : -gt
> 1+1 -gt 1
True

Example : -ge
> 1+1 -ge 2
True

Example : -lt
> 1+1 -lt 3
True

Example : -le
> 1+1 -le 2
True

Example : -like
> "Hello" -like "Hell*"
True

Example : -notlike
> "Hello" -notlike "Hea*"
True


Example : -match
>
"two words" -match 'two (\w+)'
True
> # capturing groups () results saved in array $matches
> $matches
Name       Value
----       -----
1          words
0          two words

Example : -notmatch
> "two words" -notmatch 'three \w+'
True

Example: -contains
> 1,2,3,4,5 -contains 3
True

Example : -notcontains
> 1,2,3,4,5 -notcontains 6
True

Example : -in
> "windows" -in "windows","unix"
True
> "windows" -in "android","unix"
False

Example : -notin
> "windows" -notin "android","unix"
True
> "windows" -notin "windows","unix"
False

Example : -replace
> "abcde" -replace "bc", "TEST"
aTESTde

Go Top

Assignment Operators

=     Sets variable to the specified value

+=    Increases variable by the specified value
      or appends the specified value to the existing
      value

-=    Decreases variable by the specified value

*=    Multiplies variable by the specified value
      or appends the specified value to the existing
      value

/=    Divides variable by the specified value

%=    Divides variable by the specified value and
      then assigns the remainder (modulus) to the
      variable

++    Increases variable by 1.
      Can be placed before or after variable
      Before: increments before using the result
      After: increments after result is used

--    Decreases variable by 1
      Can be placed before or after variable
      Before: decrements before using the result
      After: decrements after result is used

Example: =
$s = "powershell"
$i = 7
$processes = Get-Process

Example: +=
$s = ""
# increment (concatenate) strings
$s += "string"
# increment integers
$i = 0
$i += 7
# adds collection of objects
$c = Get-Process
$c += Get-Service
# appends an array
$a = 1,2,3
$a +=4
# appends a hashtable
$h = @{one = 1; two = 2; three = 3}
$h += @{four = 4}

Example: -=
#
$i = 7
$i -= 2

Example: *=
# integers multiplied by the specified value
$i = 7
$i *= 2
> # strings, repeated by the "specified value" times
> $s = "hello"
> $s *= 3
> $s
hellohellohello

Example: /=
$i = 4
$i /= 2

Example: %=
> $a = 7
> $a %= 4
> $a
3

Example: ++
> $a = 5
> $b = 5
> $c = ++$a
> $d = $b++
> $c
6
> $d
5

Example: --
> $a = 5
> $b = 5
> $c = --$a
> $d = $b--
> $c
4
> $d

Go Top

Logical Operators

-and     logical AND
         True when both statements are True

-or      logical OR
         True when either statement is True

-xor     logical XOR
         True when only one statement is True

-not     logical NOT
         Negates the Statement.  True when statement
         is False and vice versa

!        logical NOT
         Same as -not

Example : -and
> ("a" -in "a","b","c") -and ("b" -in "a","b","c")
True
> ("a" -in "a","b","c") -and ("d" -in "a","b","c")
False

Example : -or
> ("a" -in "a","b","c") -or ("b" -in "a","b","c")
True
> ("a" -in "a","b","c") -or ("d" -in "a","b","c")
True

Example : -xor
> ("a" -in "a","b","c") -xor ("b" -in "a","b","c")
False
> ("a" -in "a","b","c") -xor ("d" -in "a","b","c")
True

Example : -not
> -not ("a" -in "a","b","c")
False
> -not ("d" -in "a","b","c")
True

Example : !
> !("a" -in "a","b","c")
False
> !("d" -in "a","b","c")
True

Go Top

Bitwise Operators

-band     Bitwise AND

-bor      Bitwise OR

-bxor     Bitwise XOR

-bnot     Bitwise NOT

-shl      Bitwise shift left

-shr      Bitwise shift right

Example : -band
# 11111111 Bitwise AND with 00001111
# ans: 00001111
> 255 -band 31
31


Example : -bor
# 11111111 Bitwise OR with 00001111
# ans 11111111
> 255 -bor 31
255

Example : -bxor
# 11111111 Bitwise OR with 00001111
# 11110000
255 -bxor 31
224

Example : -bnot
# Bitwise NOT is unary
# produces binary complement of a value
# 1->0, 0->1
# 32 bit signed integer
# 2147483647 
# = 0x7FFFFFFF = 01111111 11111111 11111111 11111111
# -2147483648
# = 0x80000000 = 10000000 00000000 00000000 00000000
> -bnot -2147483648
2147483647
> -bnot 2147483647
-2147483648

Example : -shr
# [dec] 21   = (bin) 0001 0101
#
# shift right 1 =>   0000 1010 = (dec) 10
> 21 -shr 1
10
# shift right 2 =>   0000 0101 = (dec) 5
> 21 -shr 2
5

Example : -shl
# [dec] 21   = (bin) 0001 0101
#
# shift left 1 =>   0010 1010 = (dec) 42
> 21 -shl 1
41
# shift left 2 =>   0101 0100 = (dec) 84
> 21 -shl 2
84

 

Go Top

Other Operators

-split    Splits a string

-join     Joins multiple strings

..        Range operator

-is       Type evaluator (Boolean)
          Tells whether object IS an instance
          of a specified .NET Framework type

-isnot    Type evaluator (Boolean)
          Tells whether object is NOT an instance
          of a specified .NET Framework type

-as       Type convertor.
          Tries to convert to the specified type

-f        String format operator
          Formats using the format method of string
          objects

[]        Cast operator.  Converts to the
          specified type

,         Comma operator (Array constructor)

.         Dot-sourcing operator.
          Runs a script in currentt scope

$()       Sub-expression operator         

@()       Array sub-expression operator. Return the
          result of one or more statements as an
          array.  If only one item, the array has one
          member

&         The call operator.
          a.k.a invocation operator.
          Lets you run commands that are
          stored in variables and represented by
          strings

 

Example : -split
> "abc,def" -split ","
abc
def

Example : -join
> "abc","def" -join ";"
abc;def

Example : ..
> 1..5 | foreach {$_ *5}
5
10
15
20
25

Example : -is
> 7 -is [int]
True

Example : -isnot
> "seven" -isnot [int]
True

Example : -as
> $a=7
> $a.GetType().Name
Int32
> $b=7 -as [string]
> $b.GetType().Name
String

Example : -f
> "{0:N2}" -f 7
7.00

Example : [ ]
> [datetime]$a = "1/1/2000"
> $a.GetType().Name
DateTime

Example : ,
> $myarray=1,2,3,4,5
> $myarray
1
2
3
4
5

Example : .
> . c:\scripts\hello.ps1
Hello from myscript
> # Note the space between dot operator and the script path

Example : $()
> "Today is $(Get-Date)"
Today is 02/15/2020 11:31:36

Example : @()
> @(Get-CimInstance win32_logicalDisk)

DeviceID DriveType ProviderName VolumeName Size         FreeSpace
-------- --------- ------------ ---------- ----         ---------
C:       3                                 747748646912 445228175360
E:       5

Example : &
$a = "Get-Process"
& $a
# will return the outputs of Get-Process cmdlet

Go Top

Redirection Operators

>         Send particular type of output to
          files and output streams. 
          Overwrite, if stream exists

>>        Send particular type of output to
          files and output streams. 
          Append, if stream exists
      

Note: output streams are:

*         All output
1         Success output
2         Errors
3         Warning messages
4         Verbose output
5         Debug messages

 

Examples

# write warning output to warning.txt
Do-Something 3>warning.txt

# appends verbose output to verbose.txt
Do-Something 4>>verbose.txt

# writes debug output to ouput stream
Do-Something 5>&1

# redirects all output to out.txt
Do-Something *>out.txt

 

Go Top

Variables and Data Types  
 

 

Go Top

 

Arrays  
Initialization

$A = 1,2,3,4,5
[int32[]]$A = 1,2,3,4,5

$B = 1..5              # generated by range operator

$C = @()               # empty array
$C = @(1,2)
$C = @(Get-Process)    # output from other cmdlet

$D = 1,(2,3),4         # array within array

 

Go Top

Array operations

# sample array
> $a = 1,2,3,4,5

# first element
> $a[0]
1

# last element
> $a[-1]
5
> $a[$a.length-1]
5

# last 3 elements
> $a[-3..-1]
3
4
5

# first 3 elements
> $a[0..2]
1
2
3

# reversing the array
> $a[($a.length-1)..0]
5
4
3
2
1

# mutliple range of indices
$a=0..9
> $a[1,3+6..9]
0
3
6
7
8
9

# applying filters with where
(0..9).Where{ $_ % 2 }

# concatenation
> $a = 1..3
> $b = 4..66
> $c = $a + $b
> $c
1
2
3
4
5
6
 

Go Top

Iteration

$a = 0..9
foreach ($element in $a)
{   $element } 

$a = 0..9
for ($i = 0; $i -le ($a.length - 1); $i += 2)
{   $a[$i] } 

$a = @(0 .. 3)
$a.ForEach({ $_ * $_})

Go Top

Properties

$a = 0..9 

$a.Count 
10

$a.Length
10

Go Top

Hashtables / Ordered Dictionary
 

Initialization

# Hashtable
$myhashtable = @{<name>=<value>;[<name>=<value>] ..} 

# Ordered Dictionary
$myorddict = [ordered]@{<name>=<value>;[<name>=<value>] ..}

Examples for Hashtable

# Hashtable - key, value pairs on different line
$MonthDays = @{
    "Jan" = "31"
    "Feb" = "28"
    "Mar" = "31"
    "Apr" = "30"
    "May" = "31"
    "Jun" = "30"
    "Jul" = "31"
    "Aug" = "31"
    "Sep" = "30"
    "Oct" = "31"
    "Nov" = "30"
    "Dec" = "31"
  }

# Hashtable - new key,value pair separated by ";"  
$myhash = @{name="Tom"; age="35"}

Example for Ordered Dictionary 
# Ordered Dictionary
$digits = [ordered]@{one=1;two=2;three=3;four=4;five=5}  

Go Top

Accessing

Examples

#Using the following hash for the example
$myhash = @{name="Tom"; age="35"}

 

> $myhash.keys
name
age

> $myhash.values
Tom
35

> $myhash

Name     Value
----     -----
name     Tom 
age      35 

> $myhash['name']
Tom

> $myhash.name
Tom

 

 

Go Top

Properties  
Methods

 

Go Top

Flow Control - Looping  

While

Runs script block while conditional test is true

 $a = 0
While ($a –lt 10) {$a; $a++}

$ComputerName = '2012R2-DC'
Restart-Computer -ComputerName $ComputerName
Start-Sleep -Seconds 30
While (-not (Test-Connection -ComputerName $ComputerName -Quiet))
{
"Waiting on restart: $ComputerName"
Start-Sleep -Seconds 30
}

Go Top

Do While

Condition evaluated AFTER script block runs at least once. 
Runs script block if conditional test = true

$a = 0
Do {$a; $a++} While ($a -le 5)

$ComputerName = '2012R2-DC'
Restart-Computer -ComputerName $ComputerName
Do
{
"Waiting on restart: $ComputerName"
Start-Sleep -Seconds 30
}
While (-not (Test-Connection -ComputerName $ComputerName -Quiet))

Go Top

Do Until

Condition evaluated AFTER script block runs at least once. 
Runs script block if conditional test = false

Do {$a; $a++} Until ($a –gt 10)

$ComputerName = '2012R2-DC'
Restart-Computer -ComputerName $ComputerName
Do
{
"Waiting on restart: $ComputerName"
Start-Sleep -Seconds 30
}
Until (Test-Connection -ComputerName $ComputerName -Quiet)

Go Top

For

Runs script block while conditional test = true
Useful when targeting a subset of array values

For (<init>; <condition>; <increment>) {<statement list>}

eg. 1 for($i=0;$i -le 5;$i++) 
{ write-host "line $i" }

eg. 2
$Computers = @(Get-ADComputer -Filter
{OperatingSystem -like "*server*"}).Name
For ($i=0 ; $i -lt $Computers.Length ; $i++)
{
"Computer $($i+1): $($Computers[$i])"
}


Go Top

ForEach

Good when targeting all array values

ForEach ($<item> in $<collection>){<statement list>}

eg. 1
ForEach ($file in Get-Childitem c:\windows -File)
{$file.name}

eg. 2
$Services = Get-Service
ForEach ($Service in $Services)
{ $Service.Name + ' is ' + $Service.Status }

Go Top

Flow Control - Branching  

If
If (<test1>)
{
<statement list 1>
}

If-Else
If (<test1>)
{
<statement list 1>
}
Else
{
<else statement list>
}

If-Elseif
If (<test1>)
{
<statement list 1>
}
ElseIf (<test2>)
{
<statement list 2>
}
ElseIf (<test3>)
{
<statement list 3>
}

If-Elseif-Else
If (<test1>)
{
<statement list 1>
}
ElseIf (<test2>)
{
<statement list 2>
}
Else
{
<else statement list>
}

$Language = (Get-CimInstance -class win32_operatingsystem).OSLanguage

example for If
if ($Language -eq "1033")
{write-Host "Language = English US" -ForegroundColor Magenta}

example for if-else
if ($Language -eq "1033")
{write-Host "Language = English US" -ForegroundColor Magenta}
else
{Write-Host "Another Language" -ForegroundColor Cyan}

example for if-elseif
if ($Language -eq "1033")
{
Write-Host "Language = English US" -ForegroundColor Magenta
}
elseif ($Language –eq "1078")
{
Write-Host "Language = Afrikaans" -Foregroundcolor Green
}

example for if-elseif-else
if ($Language -eq "1033")
{
Write-Host "Language = English US" -ForegroundColor Magenta
}
elseif ($Language –eq "1078")
{
Write-Host "Language = Afrikaans" -Foregroundcolor Green
}
else
{
Write-Host "Another Language" -ForegroundColor Cyan
}

 

Go Top

Switch

Switch (<test-value>)
{
<condition 1> {<action 1>}
<condition 2> {<action 2>}
}

Switch . . . Default

Switch (<test-value>)
{
<condition 1> {<action 1>}
<condition 2> {<action 2>}
Default {<action 3>}
}

Switch -Wildcard

Switch (<test-value-array>)
{
<condition 1> {<action 1>}
Default {<action 2>}
}

Switch -CaseSensitive

Switch -Regex

Switch -File

 

$DomainRole = (Get-CimInstance -class Win32_ComputerSystem).DomainRole
 

switch ($DomainRole)
{
0 {write-Host "standalone workstation"}
2 {write-Host "standalone server"}
}

switch ($DomainRole)
{
0 {write-Host "standalone workstation"}
2 {write-Host "standalone server"}
Default {write-Host "other domain role"}
}

$FileNames = (Get-ChildItem C:\Windows).FullName
Switch -Wildcard ($FileNames)
{
"*.exe" {"Found executable: $_"}
Default {"Not an exe: $_"}
}

switch -CaseSensitive ("HELLO")
{
"hello" {"lowercase"}
"HELLO" {"uppercase"}
}

switch –Regex (Get-ChildItem -Path c:\)
{
"^program" {Write-Host $_ -ForegroundColor Green}
"s$" {Write-Host $_ -ForegroundColor Cyan}
}

switch -File .\servers.txt
{
"server1" {Write-Host "$_ is in file" -ForegroundColor Green}
"server10" {Write-Host "$_ is in file" -ForegroundColor Cyan}
}

Go Top

Break

is the statement used to immediately exit a Foreach, For, While, Do, or Switch statements

Switch –Wildcard ("WMF 5.0")
{
   "WMF 5.0" {"Matched First"; Break }
     "W*" {"Matched Second"}
}

Go Top

Continue

$c = 0
While ($c -lt 3)
{
$c++
if ($c -eq 2) {Continue}
Write-Host $c
}

Go Top

Return

Exits current „scope‟, which can be a function, script, or script block
Note: Return can appear alone or followed by a value or expression

function Test-Return ($val)
{
if ($val -ge 5) {return $val}
Write-Host "Reached end of function"
}

Exit

Exit current script or session – Optional ErrorLevel Numeric Code

PS C:\> Exit 10

 

Go Top

Scope  

variable scope modifier

$[<scope-modifier>]:<name> = <value>

scope-modifiers are:

global: - Specifies that the name exists in the Global scope.

local: - Specifies that the name exists in the Local scope. The current scope is always the Local scope.

private: - Specifies that the name is Private and only visible to the current scope.

script: - Specifies that the name exists in the Script scope. Script scope is the nearest ancestor script file's scope or Global if there is no nearest ancestor script file.

using: - Used to access variables defined in another scope while running scripts via cmdlets like Start-Job and Invoke-Command.

workflow: - Specifies that the name exists within a workflow. Note: Workflows are not supported in PowerShell Core.
 

function scope modifier

function [<scope-modifier>]:<name>
{<function-body>}

Dot Source Notation

. <scriptname>

By default, child scope created when script or function runs, but prefixing with dot and space (i.e. Dot-source) does not create a child scope

eg. 1
$global:a = "one"

eg. 2

PS C:\> . C:\Scripts\FunctionExample.ps1

PS C:\> . C:\FunctionInScript.ps1
PS C:\> Get-ServerData -ComputerName 2012R2-DC
SystemDirectory Organization BuildNumber RegisteredUser
--------------- ------------ ----------- --------------
C:\WINDOWS\s... 9600 administrator@

=> Function is available after script runs

Go Top

 

Modules  
   

 

Output formatting
 

The syntax for -f format operator is

{<index>[,<alignment>][:<formatString>]}

Format Strings Description
C Currency
X Display Number in Hexa Decimal
p Display Number as Percentage
n Display with width n to left side
-n Display with width -n to right side
dn Display Numbers Padded by 0 by n times
# Digit placeholder,
, Thousand separator
\ Escape Character
:ddd Day of Week
:dd Day of Month
:dddd Full name of Day of Week
:hh Hour
:HH Hour in 24 Hour format
:mm Minutes
:SS Seconds
:MM Month in Number
:MMMM Name of the Month
:yy Year in short
:yyyy Full year
"{index}" -f $first,$second, ...$last   
#where index starts from 0

Special Characters

Chr  Desc
`0   Null
`a   Alert
`b   Backspace
`f   Form feed
`n   New line
`r   Carriage return
`t   Horizontal tab
`v   Vertical tab
Examples
$message = "Hello, $first $last."

$message = "Date: $(Get-Date)"

'Hello, {0} {1}.' -f $first, $last

'Hello, {0} {1}.' -f $values

"{0:yyyyMMdd}" -f (get-date)
"Population {0:N0}" -f  8175133

$servers  -join ','

$text = "NAME=#FULL_NAME#, ADDRESS=#ADDRESS# ..."
$text = $text -replace '#FULL_NAME#', 'John Doe'





















 
 
 

Go Top

 

Date & Time  

Syntax:

Get-Date [[-Date] <datetime>] [-Year <int>] [-Month <int>] [-Day <int>] [-Hour <int>] [-Minute <int>] [-Second <int>] [-Millisecond <int>] [-DisplayHint <DisplayHintType>] [-Format <string>] [<CommonParame
ters>]

Properties:

(get-date).day
(get-date).dayofweek
(get-date).dayofyear
(get-date).hour
(get-date).millisecond
(get-date).minute
(get-date).month
(get-date).second
(get-date).timeofday
(get-date).year

 

#Retrieve the current date and time, but display only the date:
> get-date -DisplayHint date
Tuesday, November 26, 2019

#Retrieve the current date and time in specific format
> get-Date -format "dd-MMM-yyyy HH:mm"
26-Nov-2019 18:06

#Retrieve the current date and time, display as a General short date/time:
> get-date -format g
11/26/2019 6:06 PM

#Display the day of the year:
> (get-date).dayofyear
330

#Get the day of the week as an integer (0=Sunday, 6=Saturday):
> [Int]$dow = Get-Date | Select-Object -ExpandProperty DayOfWeek
> $dow
2

# Display yesterdays date, using the .AddDays method:
> (get-date).AddDays(-1)
Monday, November 25, 2019 6:09:10 PM

# Get a specific date:
> Get-Date -date "2018-02-28"
Wednesday, February 28, 2018 12:00:00 AM

# Display daylight savings and UTC:
> (get-date).IsDaylightSavingTime()
False
> (get-date).ToUniversalTime()
Tuesday, November 26, 2019 10:10:39 AM
# or display in ISO 8601 format:
> (get-date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm:ss')
2019-11-26 10:10:39

Go Top

 

Strings  

String operations

s.split(separator)

Example

PS> "mon 1,mon 2,mon 3".split(",")

mon 1
mon 2
mon 3

 Go Top

Files & Directories  

Split-Path

returns only the specified part of a path, such as the parent directory, a   child directory, or a file name

More details from Get-Help Split-Path

E.g. get only filename part

PS> split-path -Path "c:\mydir\subdir\myfile.ext" -Leaf
myfile.ext

E.g. resolve the wildcard

PS> split-path "C:\Test\Logs\*.log" -leaf -resolve
Pass1.log
Pass2.log
...

eg. get only the parent

PS> split-path -Path "c:\mydir\subdir\myfile.ext"
c:\mydir\subdir

Go Top

Set-Location

Change to the specified directory

eg.
PS> Set-Location c:\temp

Get-Location

Get current directory

eg.
PS> Get-Location
c:\temp
Get-ChildItem
 

 

Go Top

Providers & Drives

Providers - exposes data from specialized data store

Drives - can be accessed using the -Path parameter on a *-*Item Cmdlet e.g. GetChildItem -Path <drive>

 

 Get-PSProvider
: List all of the currently installed providers instances.  These (instances) are referred to as Drives

Example

Get-PSDrive
:: Lists all provider instances (Drives)

Example

Go Top

   

try ... catch ... finally

Try {
   # Do something tricky
}

Catch {
   # Run this if a terminating error occurred in the Try block
   # The variable $_ represents the error that occurred
   $_
}

Finally {
   # Always run this at the end
}

 

Example

try {
   $wc = new-object System.Net.WebClient
   $wc.DownloadFile("http://www.contoso.com/MyDoc.doc","c:\temp\MyDoc.doc")
}
catch [System.Net.WebException],[System.IO.IOException] {
    "Unable to download MyDoc.doc from http://www.contoso.com."
}
catch {
    "An error occurred that could not be resolved."
}
finally {
    "While trying to download http://www.contoso.com/MyDoc.doc and save"
}

 Go Top

Class

- added in powershell 5.0.  A formal syntax to define classes and other user-defined types

 

 

Defining a class

class  
class <class-name> [: [<base-class>][,<i/f-list]] {
[[<attr>] [hidden] [static] <property-def> ...]
[<class-name>([<constructor-arg-list>])
{<constructor-statement-list>} ...]
[[<attr>] [hidden] [static] <method-def> ...]
}

Example

class Device {
    # attributes
    [string]$Brand     
    [string]$Model
    [string]$VendorSku

    # method(s)
    [string]ToString(){
        return ("{0}|{1}|{2}" -f $this.Brand, $this.Model, $this.VendorSku)
    }
}

 

Go Top

Instantiating a class

[$<var-name> =] New-Object -TypeName <class-name> [
  [-ArgumentList] <constructor-arg-list>]

or

[$<var-name> =] [<class-name>]::new([<constructor-arg-list>])

 

Example

$surface = [Device]::new()
$surface.Brand = "Microsoft"
$surface.Model = "Surface Pro 4"
$surface.VendorSku = "5072641000"

 

Go Top

 Miscellaneous  
assembly  using assembly <.NET-assembly>

Example :
PS C:\> using assembly System.Windows.Forms
PS C:\> using namespace System.Windows.Forms
PS C:\> [MessageBox]::Show("Hello, world!")



Example : using WinSCP .NET assembly in powershell

see https://winscp.net/eng/docs/library_powershell

Go Top

base

For invoking a base class constructor from a subclass

 

Example

class Person {
    [int]$Age

    Person([int]$a)
    {
        $this.Age = $a
    }
}

class Child : Person
{
    [string]$School

    Child([int]$a, [string]$s ) : base($a) {
        $this.School = $s
    }
}

[Child]$littleone = [Child]::new(10, "Silver Fir Elementary School")

$littleone.Age

 

Configuration

Used in Desired State Configuration (DSC)


Configuration [[-ResourceModuleTuplesToImport] <List[Tuple[string[],ModuleSpecification[],version]]>] [[-OutputPath] <Object>] [[-Name] <Object>] [[-Body] <scriptblock>] [-ArgsToBody] <hashtable>] [[-ConfigurationData] <hashtable>] [[-InstanceName] <string>]  [<CommonParameters>]

Example : here

data [<variable-name>] [-supportedCommand <cmdlet-name>]  
{            
     <Permitted content>
}     # More info PS> get-help about_Data_Sections

Examples : data

DATA {   
       "Thank you for using my visiting my website."
       "I the knowledge and information share is useful."
       "I appreciate your comments and feedback."
}

Go Top

dynamicparam {
     <statement-list>
}
# More info PS> get-help about_Functtions_Advanced_Parameters

Dynamic parameters, are only available at run time.

They are actually built on the fly when calling the function

 

 

 

 

 

Go Top

enum <enum-name> {
    <label> [= <int-value>]
    ...
}
# More info PS> get-help about_enum

enum is used to declare an enumeration;  a distinct type that consists of a set of named labels  called the enumerator list.

Enumerations are internally represented as integers with a starting value of zero. The first label in the list is assigned the value zero. The remaining labels are assigned with consecutive numbers.

In the definition, labels can be given any integer value. Labels with no value assigned take the next integer value.

 

 

 

 

 

 

 

 

Go Top

filter [<scope:>]<name> {<statement list>}

A filter is a special kind of function that uses the Filter keyword,
It runs on each object in the pipeline
 

 

 

Example

# define the filter
filter EncloseQuotes {
   """$_"""
}

# use the filter to process the pipeline
@(1,2,3) | EncloseQuotes

output
"1"
"2"
"3"

Go Top

hidden

The hidden keyword can hide properties, methods (including constructors, events, alias properties, and other member types, including static members, from the default results of the Get-Member cmdlet, and from IntelliSense and tab completion results

Example : hidden

class Car
{
   # Properties
   [String] $Color
   [String] $ModelYear
   [int] $Distance

   # Method
   [int] Drive ([int]$miles)
   {
      $this.Distance += $miles
      $this.rides++
      return $this.Distance
   }

   # Hidden property of the Drive method
    hidden [int] $rides = 0
}

 

Go Top

Inlinescript

The InlineScript activity runs commands in a shared PowerShell session's workflow. InlineScript is only valid in workflows.

InlineScript {<script block>} <ActivityCommonParameters>

more info here

Example

workflow Test-Workflow {
  $a = 3

  ## Without $Using, the $a workflow variable isn't visible
  ## in inline script.
  InlineScript {"Inline A0 = $a"}

  ## $Using imports the variable and its current value.
  InlineScript {"Inline A1 = $Using:a"}
}

Test-Workflow

Go Top

module

using module <module-name>

The using module command imports the module and also loads the class definitions

more details here

Example

# assume that we have a module named CardGames that defines the following classes
# CardGames.Deck
# CardGames.Card

using module CardGames
using namespace CardGames

[Deck]$deck = [Deck]::new()
$deck.Shuffle()
[Card[]]$hand1 = $deck.Deal(5)
[Card[]]$hand2 = $deck.Deal(5)
[Card[]]$hand3 = $deck.Deal(5)

namespace

using namespace <.NET-namespace>

more details here

Example

using namespace System.Text
using namespace System.IO

[string]$string = "Hello World"
## Valid values are "SHA1", "SHA256", "SHA384", "SHA512", "MD5"
[string]$algorithm = "SHA256"

[byte[]]$stringbytes = [UnicodeEncoding]::Unicode.GetBytes($string)

[Stream]$memorystream = [MemoryStream]::new($stringbytes)
$hashfromstream = Get-FileHash -InputStream $memorystream `
  -Algorithm $algorithm
$hashfromstream.Hash.ToString()

parallel

Describes a script block where the activities in the block runs in parallel as they are independent.  The keyword is used in a workflow.

 

throw

Syntax:

throw [<expression>]

more details here

Example

# the Throw keyword in the parameter subexpression makes
# the Path parameter a required parameter in the function
function Get-XMLFiles
{
  param ($path = $(throw "The Path parameter is required."))
  dir -path $path\*.xml -recurse |
    sort lastwritetime |
      ft lastwritetime, attributes, name  -auto
}

Example  if (-not (Test-Path -Path C:\DoesNotExist.txt)) {
throw 'The file does not exist'
} else {
Write-Host 'The file does exist'
}

Go Top

trap

trap [[<error type>]] {<statement list>}

The Trap statement includes a list of statements to run when a terminating error occurs. A Trap statement consists of the Trap keyword, optionally followed by a type expression, and the statement block containing the list of statements to run when an error is trapped. The type expression refines the types of errors the Trap catches

Example 1 - trap with break

function break_example {
    trap {
        "Error trapped"
        break
    }
    1/$null
    "Function completed."
}
# call the function
break_example


output
Error trapped
Attempted to divide by zero.
At line:4 char:7

Example 2 - trap with continue

function continue_example {
    trap {
        "Error trapped"
        continue
    }
    1/$null
    "Function completed."
}
# call the function
continue_exampl
e


output
Error trapped
Function completed.

Go Top

type

is the alias for Get-Content - displays the contents of the file

 

 

 

Go Top

workflow

workflow <Verb-Noun>
{
Parallel
{
[<Activity>]
[<Activity>]
...
}
} # more info here

Example

workflow Test-Workflow
{
    Parallel
    {
         Get-Process
         Get-Service
    }
}

Go Top

 

Automatic Variables  

These variabls store state information for Powershell.  These variables are created and maintained by PowerShell.  More info here

Variable Contains
$$ The last token in the last line received by the session
$? Execution status of the last command
$^ First token in the last line received by the sesion
$_ The current obtain in the pipeline obtain.  Same as $PSItem
$args An array of values for undeclared parameters that are passed to a function, script of script block
$ConsoleFileName Path of the console file (.psc1) that was most recently used in the session
$Error An array of error objects representing the most recent errors.  The most recent error is $Error[0]
$Event PSEventArgs object that represents the event that is being processed
$EventArgs An object that represents the first event argument that derives from EventArgs of the event that is being processed
$EventSubscriber PSEventSubscriber object that represents the event subscriber of the event that is being processed
$ExecutionContext an EngineIntrinsics object that represents the execution context of the PowerShell host
$false False. Variable to represent the value of False
$foreach the enumerator (not the resulting values) of a ForEach loop. The $ForEach variable exists only while the ForEach loop is running; it's deleted after the loop is completed
$HOME full path of the user's home directory
$Host an object that represents the current host application for PowerShell
$input an enumerator that enumerates all input that is passed to a function. The $input variable is available only to functions and script blocks (which are unnamed functions
$LastExitCode hash table of any string values that were matched by the -match or -notmatch operator. The $Matches hash table can also be populated with captures when you use regular expressions with the -match operator.
$Matches information about the current command, such as the name, parameters, parameter values, and information about how the command was started, called, or invoked, such as the name of the script that called the current command
$MyInvocation Information about the current command, such as the name, parameters, parameter values, how the command was started, etc
$NestedPromptLevel The current prompt level.  0 indicates the original prompt level.  value is incremented when you enter a nested level and decremented when you exit
$null Contains a null or empty value
$PID The process identifier of the process that is hosting the current PowerShell session
$PROFILE Full path of the PowerShell profile for the current user and the current host application
$PSBoundParameters Dictionary of the parameters that are passed to a script or function and their current values.  The variable has a value only in a scope where parameters are declared e.g. a script or function.
$PSCmdlet Object that represents the cmdlet or advanced function that's being run
$PSCommandPath Full path and file name of the script thats being run
$PSCulture The name of the culture currently in use in the operating system.  The culture determines the display format of items such as numbers, currency, and dates.
$PSDebugContext Information about the debugging environment. 
$PSHOME The full path of the installation directory for PowerShell
$PSItem Same as $_.  The current object in the pipeline object.  Can use this variable to perform an action on every object or on selected objects in a pipeline
$PSScriptRoot The directory from which a script is being run
$PSSenderInfo Information about the user who started the PSSession.
$PSUICulture The name of the user interface culture that's currently in use in the OS.
$PSVersionTable Read only hash table of details about the version of the PowerShell running in the current session
$PWD A path object that represents the current dir.
$Sender Object that generated this event.  The variable is populated only within the Action block of an event registration command
$ShellId Identifier of the current shell
$StackTrace Stack trace for the most recent error
$switch Enumerator of the switch statement.  Exists only while the switch statement is running. 
$this defines the script property or method.  refers to the object that is being extended.
$true True.  Variable to represent the value of True

 

 

Example : $PSVersionTable

> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.18362.628
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.18362.628
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

 Go Top