Bra*_*ady 3 powershell path output
我有以下一点代码 -
Set-Location "$PSCommandPath"
Write-Host "Starting script."
Write-Host "Current directory is... $PSCommandPath"
Run Code Online (Sandbox Code Playgroud)
这只是返回 -
Starting script.
Current directory is...
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
如果我不得不猜测,您运行的是不支持的旧版PowerShell $PSCommandPath.该变量仅适用于3.0及更高版本.从文档:
$PSCommandPath包含正在运行的脚本的完整路径和名称.此参数在所有脚本中都有效.Windows PowerShell 3.0中引入了此自动变量.
因此,像所有未定义的变量一样,$PSCommandPath被视为$null:
PS > ($undefined).GetType()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ ($undefined).GetType()
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PS >
PS > $var = 123
PS > Write-Host "My variable: $var"
My variable: 123
PS > Write-Host "My variable: $undefined"
My variable:
PS >
Run Code Online (Sandbox Code Playgroud)
要解决此问题,您需要将PowerShell升级到3.0或更高版本.
此外,它似乎你真的想要Get-Location,它返回当前的工作目录:
Write-Host "Current directory is... $(Get-Location)"
Run Code Online (Sandbox Code Playgroud)