Scripting >> Powershell >> 2.0 >>  Powershell 2.0 Cheatsheet

Work in progress ....

 

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_*

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>]

 

 Common Parameters These are parameters that are commonly available to most cmdlets
 -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

 

Commands  

get-command | foreach {$_.Name}

 Discover all available commands

 

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


Id      : 1656
Handles : 258
CPU     :
Name    : armsvc

Id      : 12512
Handles : 241
CPU     :
Name    : audiodg


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

 

Name : armsvc
Id   : 1656

Name : audiodg
Id   : 18080



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


 

 

Functions
 

function <name>
{
param ($parameter1, $paramter2)
<statement list>
}

or

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

eg. 1 - without parameters

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

invoke the function by

PS> Get-ServiceInfo

eg. 2 - with parameters

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

invoke the function by

PS> Get-ServiceInfo("Dhcp","MYCOMPUTER")

or

PS> Get-ServiceInfo -svc "Dhcp" -computer "MYCOMPUTER"

e.g. 3 with parameters and with default values for the parameters

function Get-ServiceInfo
{
param (

$svc = "Dhcp",
$computer = "MYCOMPUTER"
)
Get-Service -Name $svc -ComputerName $computer
}

when invoking the function by

PS> Get-ServiceInfo()

it is equivalent to

PS> Get-ServiceInfo("Dhcp","MYCOMPUTER")

 

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>
)

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'



 

 

 

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)

 

 

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

 

Operators  

Comparison operators

      -eq
      -ne
      -gt
      -ge  
      -lt
      -le
      -Like
      -NotLike
      -Match
      -NotMatch
      -Contains
      -NotContains
      -In
      -NotIn
      -Replace
 

 

 

Providers  
   

 

Variables and Data Types  
   

 

Arrays  
Initialization

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

$B = 1..5

$C = @()   
$C = @(1,2)
$C = @(Get-Process Notepad)



 

Accessing the array


$A[index]
$A[start..end]

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

,$a | Get-Member

 

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({ $_ * $_})

Properties
$a = 0..9 $a.Count $a.Length

 

Hashtables  

Initialization

$myhash = @{
"one" = 1
"two" = 2
}

 

 

 

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
}

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))

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)

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

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 }

 

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
}

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}
}

Break Switch –Wildcard ("WMF 5.0")
{
"WMF 5.0" {"Matched First"; Break}
"W*" {"Matched Second"}
}
Continue $c = 0
While ($c -lt 3)
{
$c++
if ($c -eq 2) {Continue}
Write-Host $c
}

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

 

Scope  

variable scope modifier

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

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

 

Modules  
   

 

Output formatting for strings  

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
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'

 

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:

PS C:\> get-date -DisplayHint date

Retrieve the current date and time:

PS C:\> $now=Get-Date -format "dd-MMM-yyyy HH:mm"

Retrieve the current date and time, display as a General short date/time:

PS C:\> get-date -format g

Display the day of the year:

PS C:\> (get-date).dayofyear

Get the day of the week as an integer (0=Sunday, 6=Saturday):

PS C:\> [Int]$dow = Get-Date | Select-Object -ExpandProperty DayOfWeek
PS C:\> $dow

Display yesterdays date, using the .AddDays method:

PS C:\> (Get-Date).AddDays(-1)

Get a specific date:

PS C:\> $mydate = Get-Date -date "2018-02-28"

Display daylight savings and UTC:

PS C:\>$a = get-date
$a.IsDaylightSavingTime()
$a.ToUniversalTime()

# or display in ISO 8601 format:
$a.ToUniversalTime().ToString('yyyy-MM-dd HH:mm:ss')

 

Strings  

String operations

s.split(separator)

Example

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

mon 1
mon 2
mon 3

 

 

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

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