ScriptBlock Flexibility in PowerShell

I decided to start sharing some of my submissions for the 2011 Microsoft Scripting Games that received decent ratings. This is my entry for Advanced Event 3, where the idea was to create a script for event log gathering. The unique part is how a single scriptblock is invoked two different ways. I don’t know that I would always integrate this into a single function, but it’s an interesting example of how flexible scriptblocks can be.

Any code that needs to reach out and touch other computers is going to benefit from PowerShell remoting. The more computers you have to connect to, the more efficient it is to use remoting. I wanted to utilize remoting the way I would in my own production environment, but I also wanted the option to use the built-in remoting capabilities found in the Get-WinEvent cmdlet. Not everyone is lucky enough to have remoting configured everywhere.

I created a scriptblock that was essentially a self-contained script with parameters. All of the actual “work” is handled in this scriptblock. The rest of the function is figuring out how to launch that scriptblock.

With the script-within-a-script ready, I just needed to launch it appropriately. The Get-LoggedEvent function has a UseRemoting switch. When this switch is specified, I want to use Invoke-Command to take advantage of PowerShell’s fan-out remoting capabilities. I pass Invoke-Command the array of names, the scriptblock and the arguments to be passed to the scriptblock. The scriptblock is given ‘localhost’ for the computer name, and Invoke-Command takes care of running a copy of the scriptblock on each computer.

If UseRemoting is not specified, I need to unwrap the array of computer names and call the scriptblock once for each computer name. This time, I need to pass the actual computer name to the scriptblock, because the built-in remoting capabilities of Get-WinEvent will be used instead of letting Invoke-Command run the scriptblock locally on each system.

With any script, there are always improvements that can be made. Bartek Bielawski (who ended up winning the 2011 Scripting Games) made a good suggestion that I use splatting for those long lists of parameters instead of backticks. He also pointed out that I don’t need to specify false as a default value for switch parameters because the value will already default to false.

Has the same effect as:

All of my entries for the 2011 Scripting Games can be found at PoshCode.

Complete Script: