powershell - 无法将参数绑定(bind)到参数 'command',因为它为空。电源外壳

标签 powershell start-job

我有一个类似于下面代码的功能。它接收命令和命令参数。我必须在后台运行这个命令并收集输出。但是最后一条语句让我犯了这个错误

错误:

Cannot bind argument to parameter 'Command' because it is null.
+ CategoryInfo          : InvalidData: (:) [Invoke-Expression], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.InvokeExpre
ssionCommand
+ PSComputerName        : localhost

代码:
$cmd = 'Get-content'
$Arg = 'path to file'
$sb = "$cmd $Arg -ErrorVariable e -ErrorAction Stop"
invoke-Expression $sb #This printsoutput
$job = Start-job -ScriptBlock {Invoke-Expression $sb}
wait-job -id $job.Id
$job | Receive-job #this should print output but throwing error

我很确定最后一行是抛出错误的那一行。

最佳答案

获得 $sb 的另一种选择除了 -argumentlist 之外的脚本 block 的范围内是使用$using:范围。 (PowerShell 3+)

$cmd = 'Get-content'
$Arg = 'path to file'
$sb = "$cmd $Arg -ErrorVariable e -ErrorAction Stop"
$job = Start-job -ScriptBlock {Invoke-Expression $using:sb}
wait-job -id $job.Id
$job | Receive-job

关于powershell - 无法将参数绑定(bind)到参数 'command',因为它为空。电源外壳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45357491/

相关文章:

windows - 如何在 PowerShell 中同时运行 2 个方法

powershell - 限制在 powershell 中运行的 Start-Process 数量

powershell - Posh-ssh 是否不适用于 Windows 任务计划程序

windows - Powershell 文件夹大小排序,自动大小转换

powershell - 如何在 PowerShell v5 模块中导出类

powershell - 表格格式、列顺序

c# - 从 C# 自定义 Cmdlet 中调用读取主机 cmdlet

powershell - 将变量传递给 Start-Job

PowerShell 作业队列

powershell - -s 在 powershell 中使用 Start-Job 时