gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:49:52 24 4
gpt4 key购买 nike

我有以下代码-

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com