Dynamically Create Script Blocks

by Dec 3, 2009

It is sometimes necessary to dynamically create script blocks. Here is an example how and why:

function Get-RemoteLog($name) {
$code = "Get-EventLog -LogName $name -Newest 5 -EntryType Error "
$sc = $executioncontext.InvokeCommand.NewScriptBlock($code)

Invoke-Command -ComputerName myServer -ScriptBlock $sc
}
Get-RemoteLog "System"

The function Get-Remotelog accepts a log name and then retrieves the last five error records from that log. Since the name of the log submitted in $name needs to be sent to the remote system, the function first has to resolve this variable locally before it creates the script block and sends it to the remote machine. If you had submitted the code directly, the remote machine would try and resolve the $name variable, which would not exist on the remote system.

Twitter This Tip! ReTweet this Tip!