Skip to content

Essential Powershell

Kenneth Kasajian edited this page Feb 21, 2017 · 2 revisions

My cheat-sheet for PowerShell from: https://ss64.com/ps/syntax.html

30 second guide

$name = 'Jon' $number = 12345 $listofnumbers = 6,7,8,9

$v = 'World' if ($v.Length -gt 0) {echo "Hello $v"} $t = (get-date -f yyyyMMddHHmmss) [System.IO.Directory]::GetCurrentDirectory() & "ipconfig.exe" cmd /c dev_OpenPalm.bat Get-Process devenv | Foreach-Object { $_.CloseMainWindow() }

Param([string]$operation, [string]$option)

$sol = [System.IO.Path]::GetDirectoryName($sol) if (!($sol.EndsWith(''))) { $sol = "$($sol)" }

if ($operation -eq 'z') { if ($o) { cp "$($sol)Test$($outdir).txt" $pr } else { cp "$($targ).zip" $prdir } }

If (10 –gt 11) { Write-Host "Yes" } elseif (11 –gt 10) { Write-Host "This time, yes" }

2 minute guide

total number of cmdlets available on the system, we can use: (get-command).count $numberofcmdlets = (get-command).count Write-Host "There are $numberofcmdlets commands available for use on this system." echo "There are $numberofcmdlets commands available for use on this system."

$alert = { "Hello World" } & $alert

10 minute guide

Print the running services in green and stopped services in red: get-service | foreach-object{ if ($.status -eq "stopped") {write-host -f red $.name $.status}` else{ write-host -f green $.name $_.status}}

Count to 10: Do { $val++ ; Write-Host $val } while($val -ne 10)

You can use carriage returns instead of semi-colons: Do { $val++ Write-Host $val } while($val -ne 10)

Count to 10: while($val -ne 10) { $val++ ; Write-Host $val }

You can use carriage returns instead of semi-colons: while($val -ne 10) { $val++ Write-Host $val }

Count to 10 but stop as soon as you reach number 5: $i = 0 while ($i -lt 10) { $i +=1 if ($i -eq 5) {break} Write-Host $i }

Count to 10 but miss out the number 5: $i =0 while ($i -lt 10) { $i +=1 if ($i -eq 5) {continue} Write-Host $i }

Retrieve the files (and folders) from the C: drive and display the size of each: get-childitem C:\ | foreach-object -process { $.length / 1024 } (The $ variable holds a reference to the current item being processed.)

Retrieve the 1000 most recent events from the system event log and store them in the $events variable: $events = get-eventlog -logname system -newest 1000

Then pipe the $events variable into the ForEach-Object cmdlet. $events | foreach-object -begin {Get-Date} -process {out-file -filepath event_log.txt -append -inputobject $_.message} -end {get-date}

Loop through an array of strings: $trees = @("Alder","Ash","Birch","Cedar","Chestnut","Elm") foreach ($tree in $trees) { "$tree = " + $tree.length }

Loop through a collection of the numbers, echo each number unless the number is 2: foreach ($num in 1,2,3,4,5) { if ($num -eq 2) { continue } ; $num }

Loop through a collection of .txt files:

foreach ($file in get-ChildItem *.txt) { Echo $file.name }

Count to 10: for($i=1; $i -le 10; $i++){Write-Host $i}

You can use carriage returns instead of semi-colons: for($i=1 $i -le 10 $i++){ Write-Host $i }

#comaprisons $demo = $null if (-Not ($demo)) { write "Zero, null or Empty"} if (!($demo)) { write "Zero, null or Empty"}

$myVar -is "String" $myVar -eq 123 $myVar -ceq $myVar2 "abcdef" -like "abc*" "abcdef" -replace "dEf","xyz" $myVar1 -is "String" -and $myVar2 -is "Int" "{2:N}" -f 24.4567 (1 -eq 1) -and -not (2 -gt 2)

$mycmd = ps | select id,ProcessName foreach ($proc in $mycmd) {"{0,-8}{1,-20}" -f $proc.id, $proc.ProcessName}

data type: To test the datatype of a value use a comparison operator: C:> 32 -is [int]

C:> $true -is [bool]

Cast a date string "09-Jun-2012" that’s in UK format and then display it as "yyyy-MM-dd" C:> [DateTime]::ParseExact("09-Jun-2012","dd-MMM-yyyy",[System.Globalization.CultureInfo]::InvariantCulture).ToString("yyyy-MM-dd") 2012-06-09

Casting To force a conversion to a specific datatype, prefix the value or variable with the type in square brackets, this is known as a Cast Operator and forces the chosen datatype:

C:> [int]"0064" C:> [int]$false C:> [byte]('0x' + 'FF')

To encode a Unicode character in a PowerShell string, prefix the unicode with 0x and cast it to System.Char:

PS > [char]0x263a

The most common DataTypes used in PowerShell are listed below.

[string] Fixed-length string of Unicode characters [char] A Unicode 16-bit character [byte] An 8-bit unsigned character

[int] 32-bit signed integer [long] 64-bit signed integer [bool] Boolean True/False value

[decimal] A 128-bit decimal value [single] Single-precision 32-bit floating point number [double] Double-precision 64-bit floating point number [DateTime] Date and Time

[xml] Xml object [array] An array of values [hashtable] Hashtable object

arrays $myArray = 1,"Hello",3.5,"World" $myArray = @(1,"Hello",3.5,"World") $var1,$var2,$var3,$var4=$myArray $myArray = 1,2,3,4,5,6,7 $myArray = (1..7) [int[]] $myArray = 12,64,8,64,12 Create an empty array: $myArray = @() Create an array with a single element: $myArray = @("Hello World") Create a Multi-dimensional array: $myMultiArray = @( (1,2,3), (40,50,60) ) $countries += 'India' $countries = New-Object System.Collections.ArrayList $countries.Add('India') > $null $countries.Add('Montenegro') > $null

Retrieve items from an Array $myArray[0] $myArray[4..9] Return the last element in an array: $myArray[-1]

Functions A block of code may be contained within a function for easy re-use. To create a function, call the function keyword followed by a name for the function, then include your code inside a pair of curly braces.

function Add-Numbers { $args[0] + $args[1] }

Add-Numbers 5 10 15

A similar function with named parameters: function Output-SalesTax { param( [int]$Price, [int]$Tax ) $Price + $Tax } C:> Output-SalesTax -price 1000 -tax 38 1038

To display the definition of a function several methods can be used: cat function:Add-Numbers or ${function:Add-Numbers} or (get-command Add-Numbers).definition

Don't add brackets around the function parameters: $result = Add-Numbers (5, 10) --Wrong! $result = Add-Numbers 5 10 --Right

A filter to display only files smaller than a given size: filter FileSizeBelow($size) { if ($.length -le $size) { $ } }

PS C:> gci \server64\workgroups -filter | FileSizeBelow 200kb PS C:> gci -recurse \server64\workgroups | ?{!$_.PSIsContainer} | FileSizeBelow 100mb

A function with default values:

function write-price { param([string]$description = "unknown", [int]$price = 100) Write-Output "$description ..... $price" } PS C:> write-price -price 250 -description Hammer Hammer ..... 250

A filter to find files owned by a specific user: filter ownedbyme { if ($.Owner -match "JackFrost") {$} } gci -recurse C:\ | Get-Acl | where {$_ | ownedbyme}

The following example shows the outline of a function that contains a Begin block for one-time preprocessing, a Process block for multiple record processing, and an End block for one-time post-processing.

Function Test-Demo { Param ($Param1) Begin{ write-host "Starting"} Process{ write-host "processing" $_ for $Param1} End{write-host "Ending"} }

Echo Testing1, Testing2 | Test-Demo Sample

Discover the methods available for an object with Get-Member For example, an integer: 123 | get-member will return the methods: CompareTo, Equals, GetHashCode, GetType, GetTypeCode, ToString

(123).equals(456) will return false (123).CompareTo(150)will return -1 (123).ToString()

"The world is everlasting" | get-member

($myStringVar1).ToLower() ($myStringVar1).equals($myStringVar2) ($myStringVar1).CompareTo($myStringVar2) ($myStringVar1).PadRight() + "**" ("a b c").split("b") ("aBCdefBCghi").split("BC") ("aBCdefBCghBi").split("[BC]") $strings = 'first','second','third' $strings -join '--'

A shortcut syntax is available (…).property that returns a single property from an item or a collection (PowerShell V3.0): (dir).FullName To return multiple properties, pipe to ForEach-Object (%) or Select-Object

Unlike simple parenthesis, a subexpression $( ) can contain multiple ; semicolon ; separated ; statements.

"The result of 2 + 3 = $(2+3)"

$(Get-WMIObject win32_Directory)

An array subexpression @( ) behaves just like a subexpression except that it guarantees that the output will be an array.

"$user.department" ==> JDOE.department "$($user.department)" ==> "Human Resources"

To find the static properties and methods of an object, use the -Static parameter of Get-Member: [datetime] | gm -static [datetime]::now [datetime]::Utcnow [system.math] | gm -static

. Dot sourcing operator run a script in the current scope so that any functions, aliases, and variables that the script creates are added to the current scope. . C:\sample1.ps1 . .\sample2.ps1

Produce a sequence of numbers: 10..20 5..25

$MyVariable = SomeValue $MyVariable = "Some String Value" [DataType]$MyVariable = SomeValue

Multiple variables can be initialised in a single line, this will create var1 and var2: $var2=($var1=1)+1

Variable names containing punctuation, can be handled with the syntax ${MyVari@ble} = SomeValue

However if the braces ${ } contain a colon ":" then PowerShell will treat the variable as a PATH and store the values directly in that file. ${C:\some_file.txt} = SomeValue

Strongly typed [int]$myPrice = 128 [string]$myDescription = "Barbecue grill" [string]$myDescription = 123 [string]$myDate = (get-date).ToString("yyyyMM") $([DateTime] "12/30/2009") $([DateTime]::Now) [datetime]$start_date=[datetime]::now.date.addDays(-5)

$myArray = "The", "world", "is", "everlasting" $varX, $varY = 64 $varA, $varB, $varC = 1, 2, 3 That will assign 1 to $varA, 2 to $varB, and 3 to $varC.

environment variables: Display the value of the COMPUTERNAME environment variable: Get-Childitem env:computername Display the values of all environment variables: Get-Childitem env: gci env: | sort name Enumerate all the environment variables: get-childitem -path env:* | get-member

$env:computername

$Computer = $env:computername $AppDataFolder = "$env:appdata" "The application data folder on computer $Computer is $AppDataFolder"

Similarly:

$windows_path = $env:Path $windows_path -split ';'

In addition to environment variables, PowerShell providers also provide access to other data and components in a similar way - resembling a file system drive. This allows you to access many different types of data in a consistent way.

Built-in Providers

Alias - Windows PowerShell aliases {Alias} Certificate - X509 certificates for digital signatures {cert} Environment - Windows environment variables {Env} FileSystem - File system drives, directories and files {filesystem} Function - Windows PowerShell functions {Function} Registry - Windows registry {HKLM, HKCU} Variable - Windows PowerShell variables {Variable}

In PowerShell a fully qualified path name takes this form:

filesystem::c:\windows\system32\shell.dll

Additional providers may also be created and installed - Get-PsProvider will list them all. Enumerate the properties of a provider with Get-psdrive: Get-psdrive Function | format-list *

e.g. to list all certificates use: Get-Childitem cert:

cd cert: gci

Automatic Variables $$ Contains the last token in the last line received by the session. $? Contains the execution status of the last operation. Equivalent to %errorlevel% in the CMD shell. See also $LastExitCode below. It contains TRUE if the last operation succeeded and FALSE if it failed. ReadOnly, AllScope $^ Contains the first token in the last line received by the session. $_ Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

Hash Tables $array_name = @{} $array_name = @{key1 = item1; key2 = item2;...} $usa_states=@{ CA="California"; "NY" = "New York"; "IL" = "Illinois"; "NH" = "New Hampshire"}

$usa_states.Add("GA", "Goregia")

$usa_states.Set_Item("GA", "Georgia")

$world_states = $usa_states + $india_states Return just the New York key (the quotes are only needed here if the key contains spaces): $usa_states.'NY'

$usa_states.ContainsKey('NY')

$usa_states.GetEnumerator() | Sort-Object Name ForEach($item in $hashtable.GetEnumerator()) {Echo $item … } ForEach($item in $hashtable.KEYS.GetEnumerator()) {Echo $item … }

pipeline: $a = Get-ChildItem *.txt foreach ($file in $a) { if ($file.length -gt 100) { Write-Host $file.name } }

Get-ChildItem *.txt | where {$_.length -gt 100} | Format-Table name

The $_ is a variable created automatically by PowerShell to store the current pipeline object. All properties of the pipeline object can be accecced via this variable.

wildcards: When recursing down through a file heirarchy, it is necessary to use the wildcard in an -include clause: Get-ChildItem c:\windows -include *.exe -recurse

Writing the above like this will fail: Get-ChildItem c:\windows*.exe -recurse the above will not match a file such as C:\windows\test\demo.exe

PS C:> Get-ChildItem c:\work*.xls PS C:> Get-ChildItem c:\work[a-f]*.txt PS C:> Get-ChildItem -literalpath 'c:\work\test[1].txt'

elevation: https://ss64.com/ps/syntax-elevate.html

Clone this wiki locally