Powershell Core reference and handy stuff

Note: “$_” is used to refer to the “current object” which is passed to foreach in the loop. And $_.name is the “name” property of the current object in the loop.

Use a list of item PIPED to a bash command 

– Echo $list_of_items | xargs -L1 bash -c ‘<some bash command’

Example: az group list

–query “[?starts_with(name,’az3000301’)]”.name –output tsv

| xargs -L1 bash -c “az group delete $0 –no-wait –yes”

Run a command-string using Invocation operator &

$c = “Get-process”

 & $c // where $c could contain a STRING like “Get-Command” or “get-process”


## Where-Object:

Get-Service | Where-Object {$_.Status -eq “Stopped”}

Get-Service | where Status -eq “Stopped”

(‘hi’, ”, ‘there’) | Where-Object Length // items with length > 0 are output

Match Type: Get-Process | where StartTime -Is [DateTime] // StartTime is of .NET type [Date] 

## OPERATORS @(….), (….), $(…)

$(..) is a SubExpression operator.. similar to how C# allows inline expressions (eg string interpolation “Hello $(name)”)

dir | foreach {“$_.GetType().FullName – $_.Name”}  // doesnt evaluate unless we put the expression in $(…) like below

dir | foreach {“$($_.GetType().FullName) – $_.Name”} // interesting that $() is only needed for the first part of the expression, not the next

() is a Grouping operator.. Returns a scalar or enumerates the expression within..

We can get “inplace enumeration” with the Subexpression operator as below (note Grouping expression iterating over dir).

PS> “Folder list: $((dir c:\ -dir).Name -join ‘, ‘)”

Folder list: Program Files, Program Files (x86), Users, Windows


And @() is an Array subexpression operator – always returns an array..

$processArray = Get-Process | Select-Object -First 1

$processArray   or $processArray.GetType().FullName  // will show it as an Object of type System.Diagnostics.Process


$processArray = @(Get-Process | Select-Object -First 1)

$processArray  // will show it as an Array of Objects  → System.Object[]


## Array Set Operations (Union, Intersect, Subtract)

$a = @(1, 2, 3)
$b = @(1, 2)
$c = @(2)

'Intersection $a  $b  $c'
$a | Where-Object {$_ -In $b} | Where-Object {$_ -In $c}

'Union $a  $b  $c'
$a + $b + $c | Select-Object -Unique

'Set difference $a - $b - $c (items in $a but not $b or $c)'
$a | Where-Object {$_ -NotIn $b} | Where-Object {$_ -NotIn $c}
Intersection $a$b$c
Union $a$b$c
Set difference $a - $b - $c (items in $a but not $b or $c)

(thanks to Jason S on StackOverflow)

Leave a Reply