powershell - 为什么 Write-Host "$PSCommandPath"没有输出我当前的路径?

标签 powershell path output

我有以下代码-

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

这只是返回-

Starting script.
Current directory is...

我该如何补救?

最佳答案

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

$PSCommandPath

Contains the full path and name of the script that is being run. This parameter is valid in all scripts. This automatic variable is introduced in Windows PowerShell 3.0.

因此,像所有 undefined variable 一样,$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)"

关于powershell - 为什么 Write-Host "$PSCommandPath"没有输出我当前的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24663243/

相关文章:

c - 我的代码给出了 Linux 上的环境变量

c++ - ld路径更新用于编译

windows - 子驱动器和文件夹

java - 如何在 Java 中格式化控制台输出并将其保存到文件?

c - 嵌套 printf 语句的奇怪输出

powershell - 如何测试特定 Active Directory 树位置是否允许使用 powershell 命令

sql - 变量名称在查询批处理或存储过程中必须是唯一的吗?

powershell - 是否可以通过脚本远程处理SSAS立方体?

mysql - 为什么 mySQL 过程在从过程内部调用时返回 null,但在单独调用时则不返回 null

powershell - 在 Yaml 管道中修复 PowerShell