6

我有一个有效的 Powershell 脚本,我想从外部文件中提取脚本块。

在职的:

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

“get-job -id | receive-job”的输出很好

不工作:

# 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)

“get-job -id | receive-job”的输出为空

winrm_scriptblock.txt 的内容正是包含在工作版本中定义的 scriptblock 变量中的大括号之间的内容。

任何帮助表示赞赏。

4

4 回答 4

11

我知道您已经有了答案,但是从脚本文件中获取脚本块的另一种方法是使用get-commandcmdlet:

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

$sb 现在是脚本的脚本块。

于 2015-01-16T21:50:10.797 回答
3

与如何将脚本块作为启动作业中的参数之一传递的答案非常相关

如果您将字符串“Get-ChildItem C:\temp”存储在文件“E:\Dashboard\Windows\winrm_scriptblock.txt”中,则此代码应输出本地计算机上文件夹“C:\temp”的内容。

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

参数

就传递参数而言,将参数传递给 powershell 中的脚本块也涵盖了该答案。正如Keith Hill所说:脚本块只是一个匿名函数

考虑以下文件内容

param(
    $number
)

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

和命令

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

会给你烦人的输出

99 lines of code in the file.
98 lines of code in the file.
97 lines of code in the file.
....
于 2015-01-16T20:55:12.780 回答
2

有什么理由不只使用 Invoke-Command 的 -FilePath 参数?

于 2015-01-16T21:05:12.217 回答
-3

您必须从 E:\Dashboard\Windows\winrm_scriptblock.txt 中提取 {}

于 2016-08-22T14:22:14.867 回答