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.
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