Splatting the ScriptBlock

After making ScriptBlock work in a splat I just had to tinker.  I had implemented it in a production script and it worked very well.  With the usual need to tinker but more importantly to revive all of the logging I wanted to find a way to include the several lines I had in the script I was previously using for the start-job.

Using a generic script to do generic tasks I started to experiment.  First was to string a few commands each separated with the semi-colon (;) which worked well but in this case would comprise of a very long line of text, defeating a huge purpose of my goal to use splatting.  Here-String had to be the answer, but how do I get that to work.  Doing some research I came across the ScriptBlock class which includes a Create method.  I then looked around the community and this seemed like an approach that would work.

$sample = @”
write-Host ‘Test’ -ForegroundColor Green
(gwmi win32_operatingsystem).Caption
write-Host ‘Completed’ -foregroundcolor Red
“@
$sb = [scriptblock]::Create($sample)
$jobdat=@{
ScriptBlock = $sb
}
invoke-Command @jobdat

So I built the here string as my sample variable, then stored it as a script block within a new variable named sb.  I included that in my splatted list of command arguments and no errors and it executed as I expected.  Now to take this simple example and apply it to my production code.

Thanks to mjolinor – “The Powershell Workbench” and Steve Murawski – “Use Powershell” for some great help.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s