Importing Scriptblock from file

kernelpanic picture kernelpanic · Jan 16, 2015 · Viewed 8.3k times · Source

I've got a working Powershell script and I'd like to have the scriptblock pulled in from an external file.

Working:

$scriptblock = { ... }
invoke-command -ComputerName $server -ScriptBlock $Scriptblock -ArgumentList $server,$team -Credential $credential -asjob -JobName Dashboard_$server -SessionOption (New-PSSessionOption -NoMachineProfile)

Output of "get-job -id | receive-job" is fine

Not working:

# Generate scriptblock from file
$file = Get-Content E:\Dashboard\Windows\winrm_scriptblock.txt
$Scriptblock = $executioncontext.invokecommand.NewScriptBlock($file)

invoke-command -ComputerName $server -ScriptBlock $Scriptblock -ArgumentList $server,$team -Credential $credential -asjob -JobName Dashboard_$server -SessionOption (New-PSSessionOption -NoMachineProfile)

Output of "get-job -id | receive-job" is empty

The contents of winrm_scriptblock.txt is exactly what is included between the braces in the scriptblock variable defined in the working version.

Any assistance is appreciated.

Answer

Mike Shepard picture Mike Shepard · Jan 16, 2015

I know you already have answers, but another way to get a scriptblock from a script file is to use the get-command cmdlet:

$sb=get-command C:\temp\add-numbers.ps1 | select -ExpandProperty ScriptBlock 

$sb is now the scriptblock for the script.