It’s a little over a month until Microsoft TechEd North America 2014 which is in Houston this year. I was trying to remember the cool stuff I saw at TechEd last year and Desired State Configuration along with the announcement about PowerShell version 4 were the two big things I remember, but let’s not forget about some of the other things such as the new Where and Foreach methods.
I certainly don’t claim to be an expert with these, but I’m going to provide a couple of examples for documentation for myself as well as to get you thinking about them:
The Where method:
1 2 3 | ((Get-Command -Name Get-WMIObject).parameters.values).where{ $_.name -eq 'ComputerName'} | Select-Object -Property Name, Aliases |
The Foreach method:
1 2 3 | ('dc01', 'sql01', 'web01').foreach{ Get-WinEvent -ComputerName $_ -LogName System -MaxEvents 1 | Select-Object -Property MachineName, Id, LevelDisplayName, Message} |
My first thought is the syntax seems to be insane, but I remember thinking the same thing years ago when I first saw the curly brace dollar sign underscore and so on: {$_.property}.
By the way, I’ll be at TechEd again this year and you probably know where you’ll find me (In the PowerShell sessions :-))
µ
The syntax for foreach is actually $foo.ForEach({}, param1, … paramN). params gets passed to the scriptblock in $args.
The syntax for where is actually $foo.Where({}, [System.Management.Automation.WhereOperatorSelectionMode]mode, [int]limit)
[System.Management.Automation.WhereOperatorSelectionMode]:
0 Default
1 First
2 Last
3 SkipUntil
4 Until
5 Split
Powershell actually allows the {} syntax on all methods that take a single scriptblock parameter. e.g. $foo.bar({}) == $foo.bar{}