Filtering Output with PowerShell

So the next thing to look at in PowerShell is how to filter output from a cmdlet. A good example is Get-Mailbox, a cmdlet that gets you information on the Exchange mailbox settings of a user. This cmdlet has dozens of properties and this gets even worse if you want to see the mailbox settings of all your users at once. Clearly you need some way of just displaying the properties you want to see and excluding the ones you don’t need. This can be done using the Select-Object cmdlet and is very simple. We simply pipe the output of Get-Mailbox into Select-Object and specify which properties we want to see.
get-mailbox | select-object

and then specify the names of the properties we want to see out of get-mailbox

So here is an example that produces a CSV file by piping the output from Select-Object to Export-CSV. Note that Select-Object has an alias, select, which I can use to abbreviate it.

 get-mailbox |select name,primarysmtpaddress,forwardingaddress,forwardingsmtpaddress,delivertomailboxandforward | export-csv -notypeinformation -path c:usersp.dunfordbbb.csv

This gives me a nice CSV list of all the users in these specific mailbox properties only.

Powershell has a lot of useful stuff to do with filtering either properties or the objects that are being returned where you are getting more than one object in a cmdlet. As we see above I used get-mailbox without specifying a particular instance. This returns all the mailboxes on the Exchange server. I could also have the option of using a query to return a set of particular mailboxes. The cmdlet to do this is Where-Object, alias where.

For example, if I want to return only those maiboxes where ForwardingAddress is set to something, I can do this using the command string below:

get-mailbox | where {$_.ForwardingAddress -ne $null}

Note in this case I’m using $_ to refer to the current object instance.

That result could then be piped into select and then to export-csv to get the list in a file as above.

PowerShell’s capabilities in filtering objects and properties are far more powerful than the old Windows command interpreter or various VBScript kludges.


Posted

in

by

Tags: