Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing Scriptblock from file

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.

like image 891
kernelpanic Avatar asked Jan 16 '15 20:01

kernelpanic


3 Answers

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.

like image 153
Mike Shepard Avatar answered Oct 13 '22 00:10

Mike Shepard


Very related to the answer from How do I pass a scriptblock as one of the parameters in start-job

If you stored the string "Get-ChildItem C:\temp" in the file "E:\Dashboard\Windows\winrm_scriptblock.txt" then this code should output the contents of the folder "C:\temp" on your local machine.

Invoke-Command -ScriptBlock ([scriptblock]::Create((Get-Content "E:\Dashboard\Windows\winrm_scriptblock.txt")))

Parameters

As far as passing parameters goes Pass arguments to a scriptblock in powershell covers that answer as well. As Keith Hill states: a scriptblock is just an anonymous function

Consider the following file contents

param(
    $number
)

$number..2 | ForEach-Object{
    Write-Host "$_ lines of code in the file."
}

And the command

Invoke-Command -ScriptBlock ([scriptblock]::Create((Get-Content "E:\Dashboard\Windows\winrm_scriptblock.txt"))) -ArgumentList "99"

Would give you the annoying output of

99 lines of code in the file.
98 lines of code in the file.
97 lines of code in the file.
....
like image 31
Matt Avatar answered Oct 12 '22 23:10

Matt


Any reason not to just use the -FilePath parameter of Invoke-Command?

like image 28
mjolinor Avatar answered Oct 13 '22 00:10

mjolinor