我有一个正在工作的Powershell脚本,我希望从外部文件中提取scriptblock。
工作:
$scriptblock = { ... }
invoke-command -ComputerName $server -ScriptBlock $Scriptblock -ArgumentList $server,$team -Credential $credential -asjob -JobName Dashboard_$server -SessionOption (New-PSSessionOption -NoMachineProfile)输出“得到工作的-id \接收-作业”很好
不工作:
# 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)“得到工作的-id \接收-作业”的输出为空
winrm_scriptblock.txt的内容正是包含在工作版本中定义的scriptblock变量的大括号之间的内容。
如能提供任何协助,我们将不胜感激。
发布于 2015-01-16 21:05:12
有理由不直接使用调用命令的-FilePath参数吗?
发布于 2015-01-16 21:50:10
我知道您已经有了答案,但是从脚本文件中获取scriptblock的另一种方法是使用get-command cmdlet:
$sb=get-command C:\temp\add-numbers.ps1 | select -ExpandProperty ScriptBlock $sb现在是脚本的脚本块。
发布于 2015-01-16 20:55:12
与How do I pass a scriptblock as one of the parameters in start-job的答案非常相关
如果您在"E:\Dashboard\Windows\winrm_scriptblock.txt“文件中存储了字符串”Get C:\temp“,则此代码将在本地计算机上输出文件夹"C:\temp”的内容。
Invoke-Command -ScriptBlock ([scriptblock]::Create((Get-Content "E:\Dashboard\Windows\winrm_scriptblock.txt")))参数
就传递参数而言,Pass arguments to a scriptblock in powershell也涵盖了这个答案。正如Keith Hill所述: scriptblock只是一个匿名函数
考虑以下文件内容
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.
....https://stackoverflow.com/questions/27992485
复制相似问题