【问题标题】:Why doesn't Write-Host "$PSCommandPath" output my current path?为什么 Write-Host "$PSCommandPath" 不输出我当前的路径?
【发布时间】:2014-08-31 01:02:27
【问题描述】:

我有以下代码-

Set-Location "$PSCommandPath"
Write-Host "Starting script."
Write-Host "Current directory is... $PSCommandPath"

刚刚返回-

Starting script.
Current directory is...

我该如何补救?

【问题讨论】:

    标签: powershell path output


    【解决方案1】:

    如果我不得不猜测,您运行的是不支持 $PSCommandPath 的旧版本 PowerShell。该变量仅在 3.0 及更高版本中可用。来自documentation

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

    要解决此问题,您需要将 PowerShell 升级到 3.0 或更高版本。


    另外,您似乎真的想要Get-Location,它返回当前工作目录:

    Write-Host "Current directory is... $(Get-Location)"
    

    【讨论】:

    • 我明白了!谢谢你。看来我正在使用 PS v2。我不想升级,因为我希望我的脚本与其他机器兼容……还是向后兼容?如果没有,有没有办法在 PS v2 中设置我的默认位置?将 Get-Location 分配给变量,然后将 Set-Location 分配给该变量?编辑-啊哈!它确实有效!
    • 正如描述所说:Contains the full path and name of the script that is being run. 因此,如果您尝试从命令行运行它,它将是 empty,因为它不在脚本中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2020-02-03
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    相关资源
    最近更新 更多