Exchange Server: Scripting Corner Volume 2 - Pipelining and the One Line command

If you are a smaller shop say 1 to 2 servers then there might not be as much value in learning to write complex PowerShell scripts. Most of what you are going to do on the server is going to be for one off situations (create storage groups, create databases, move mailboxes, etc). So for […]

If you are a smaller shop say 1 to 2 servers then there might not be as much value in learning to write complex PowerShell scripts. Most of what you are going to do on the server is going to be for one off situations (create storage groups, create databases, move mailboxes, etc). So for this installment of my scripting corner I have tried to come up with command that meet two criteria:

1) The command can be written on "one line" within PowerShell and

2) The command is something that I could generally see being used on more than one occasion by the same company.

The scenario that I came up with is one we see here on occasion; where an end user will send out an email to an unintentionally large group of users or will send a message out with information that went to a distribution group or set of users that it should not have. In both of these cases there is not a good end user powered way to get these messages back out of the Database once they have been delivered. For Exchange 2000 and 2003 we had the Exmerge tool that could extract these out for us. In Exchange 2007 we have the Export-Mailbox cmdlet.

So here we have the command that you can run that will go thru the organization and move all of these unexpected messages to a target mailbox.

Get-mailboxserver | foreach {Get-mailbox –server $_.identity -resultsize unlimited | export-mailbox –subjectkeywords "Bad Message" -targetmailbox <newmailbox> -targetfolder Deleteme –deletecontent –confirm:$false}

So let's break this one liner down for the key pieces that it uses. The biggest thing that we user here is pipelining " | ". The pipeline allows us to take the output of one cmdlet and send it directly to another cmdlet. The cmdlet further down the pipeline will need to understand the output of the proceeding cmdlet, but as long as you use a little common sense this is usually not an issue.

We are also using the foreach command to setup an execution loop. When pipelining in from another cmdlet to a foreach loop the foreach will execute against each of the outputs of the proceeding cmdlet. In other words if our get-mailboxserver returns five objects, we will execute the foreach loop five times.

This sending the output of a cmdlet into a foreach loop is one of the most common things that I end up doing when writing any script.

Full Article

Microsoft, Exchange Server, Exchange Server 2007, Scripting, Knowledgebase, Article, Tips and Tricks