【发布时间】:2019-07-26 09:42:50
【问题描述】:
为什么powershell在设置位置时认为$dir是null,而在写输出时却不是?
$command = {
param($dir)
Set-Location $dir
Write-Output $dir
}
# run the command as administrator
Start-Process powershell -Verb RunAs -ArgumentList "-NoExit -Command $command 'C:\inetpub\wwwroot'"
这会产生以下输出:
Set-Location : Cannot process argument because the value of argument "path" is null. Change the value of argument
"path" to a non-null value.
At line:3 char:2
+ Set-Location $dir
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Location], PSArgumentNullException
+ FullyQualifiedErrorId : ArgumentNull,Microsoft.PowerShell.Commands.SetLocationCommand
C:\inetpub\wwwroot
我也试过了:
$command = {
param($dir)
Set-Location $dir
Write-Output $dir
}
$outerCommand = {
Invoke-Command -ScriptBlock $command -ArgumentList 'C:\inetpub\wwwroot'
}
# run the command as administrator
Start-Process powershell -Verb RunAs -ArgumentList "-NoExit -Command $outerCommand"
但后来我得到了:
Invoke-Command : Cannot validate argument on parameter 'ScriptBlock'. The argument is null. Provide a valid value for
the argument, and then try running the command again.
At line:2 char:30
+ Invoke-Command -ScriptBlock $command 'C:\inetpub\wwwroot'
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
可能的线索:如果我设置一个局部变量而不是使用参数,它可以完美地工作:
$command = {
$dir = 'C:\inetpub\wwwroot'
Set-Location $dir
Write-Output $dir
}
# run the command as administrator
Start-Process powershell -Verb RunAs -ArgumentList "-NoExit -Command $command"
类似的 Q/As 并没有完全回答我的问题:
- PowerShell - Start-Process and Cmdline Switches(我不是在尝试使用命令行开关运行 exe,而是尝试使用需要传递参数的脚本块来运行 powershell)
-
How to use powershell.exe with -Command using a scriptblock and parameters(不使用
Start-Process,我需要以管理员身份运行) -
Powershell Value of argument path is NULL(使用
Invoke-Command而不是Start-Process)
【问题讨论】:
-
您是否有任何理由将 $command 专门传递给它,而不仅仅是像
$arguments = "-NoExit Set-Location 'C:\inetpub\wwwroot'" Start-Process powershell -Verb RunAs -ArgumentList $arguments那样在参数变量中指定位置 -
@OwainEsau,这是一个精简的例子。我的真实脚本太大太复杂,无法轻松放入字符串。
标签: powershell