We’ve all used the cmdlet Where-Object to loop through a collection of objects and filter in or out the ones we didn’t want. It’s been around since PowerShell was a pup. Its usage is a little klunky but looks essentially like this:
Get-SPSite | Where-Object { $_.owner –eq “contoso\todd” }
That statement takes the collection of objects returned by Get-SPSite and walks through each of them looking for the ones where the “owner” property is set to “contoso\todd.” The format is kind of odd, and it has one big risk, at least for an idiot like me. The code inside the curly braces actually gets executed like regular code then Where-Object looks to see if it returns a $true or $false. If you forget what the equal sign “=” does in PowerShell it can result in some hilarious things like what happened in this blog post. The current form of Where-Object lets you do things like this:
Get-SPSite | Where-Object { $_.owner = “contoso\todd” }
If you don’t use Where-Object a lot it’s an easy mistake to make. Unfortunately with that code snippet I set all the owners to contoso\todd instead of finding all the site collections whose owner is contoso\todd. The equal sign in PowerShell is assignment, not evaluation.
I’ve made that mistake a few dozen times so I’ve taken to using –like instead of –eq or =. It’s tougher for me to replace with –like with = and put the wrong one in. I’ve had significantly fewer causalities since I made this change. Not zero, mind you, but fewer. Progress is good.
Then along came PowerShell v3.
With Windows 2012 or SharePoint 2013 we get PowerShell v3. And PowerShell v3 has a newer, cooler version of Where-Object. It does all the things above, but it adds a new way to filter. In PowerShell v3 we can use the following, safer, way to find the site collections that contoso\todd owns:
Get-SPSite | Where-Object –Property owner –Value contoso\todd –EQ
It is almost impossible for me to rename all my databases or overwrite all my owners with this new syntax. Since I found out about this new syntax I’ve been using it exclusively. Combine its increased safety and the fact that you can tab complete –Property, -Value, and –EQ and it’s a winner.
Also, with PowerShell v3 not all of the Help is installed with PowerShell. You can run Update-Help to get PowerShell to download the newest, most complete version of Help for all the modules that are installed. Before you start researching the new capabilities of Where-Object, make sure you update your Help first.
tk
ShortURL: http://www.toddklindt.com/WhereObjectV3