Cannot bind parameter to argument 'command' because it is null. Powershell

孤街浪徒 提交于 2019-12-11 05:58:32

问题


I had a function similar to below code. It receives command and the command arguments. I had to run this command in background and collect the output. But that last statement is bugging me with this error

Error:

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

Code:

$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

I am pretty sure last line is the one throwing the error.


回答1:


The issue here is that you are not actually giving Invoke-Expression a command.

Whenever you create a new context ( in this case, a job ) you loose your access to the parent session's environment. In your case $sb is currently null.

The way that you manage this is to pass the values as arguments via the -ArgumentList parameter of Start-Job:

start-job -ScriptBlock {} -ArgumentList

In order to facilitate handing $sb to the ScriptBlock you would do this:

$sb = "$cmd $Arg -ErrorVariable e -ErrorAction Stop"
$job = start-job -ScriptBlock { Param([string]$sb)
    Invoke-Expression $sb
} -ArgumentList $sb

This can be confusing so this is the same code written with more friendly names:

$OuterSB = "$cmd $Arg -ErrorVariable e -ErrorAction Stop"
$job = start-job -ScriptBlock { Param([string]$InnerSB)
    Invoke-Expression $InnerSB
} -ArgumentList $OuterSB



回答2:


Another alternative to get the $sb into the scope of the scriptblock besides -argumentlist is to use the $using: scope. (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



回答3:


I got the same error but when I run PowerShell using administrator privileges, I don't get this error. Good luck!



来源:https://stackoverflow.com/questions/45357491/cannot-bind-parameter-to-argument-command-because-it-is-null-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!