Powershell 中的 $ExecutionContext.SessionState.Path.CurrentLocation 和 $pwd 有什么区别?

Whats the difference between $ExecutionContext.SessionState.Path.CurrentLocation and $pwd in Powershell?

查看我的Powershell提示功能,发现$ExecutionContext.SessionState.Path.CurrentLocation是用来获取当前路径的,这和$pwd有什么区别?

$ExecutionContext.SessionState.Path.CurrentLocation$PWD其实是有区别的

当你使用 $PWD 实际上你会得到 $ExecutionContext.SessionState.Path.CurrentLocation ,

的结果

而如果您使用 $ExecutionContext,您将获得更多 属性 关于执行上下文的信息。

PS C:\> $ExecutionContext.SessionState.Path.CurrentLocation

Path
----
C:\

PS C:\> $ExecutionContext.SessionState.Path.CurrentLocation.GetType().FullName
System.Management.Automation.PathInfo
PS C:\> $PWD

Path
----
C:\

PS C:\> $PWD.GetType().FullName
System.Management.Automation.PathInfo

所以,基本上区别在于 $ExecutionContext.SessionState.Path.CurrentLocation$PWD 需要更多的输入。

确实 $pwd$ExecutionContext 中获取了它的值。

这两个变量的主要区别在于$pwd可以被覆盖,而$ExecutionContext是常量(只读)。

$ExecutionContext 旨在模仿 cmdlet 作者可用的界面。 $pwd 只是获取当前路径的便捷方式。

因此,如果您需要获取路径而不担心任何人可能会弄乱 $pwd 的值,建议使用 $ExecutionContext