如何在 Cmdlet 中获取当前工作目录

How to get current working directory inside a Cmdlet

我正在用 C# 编写 PowerShell 的 Cmdlet。我是 subclassing Cmdlet 而不是 PSCmdlet.

有没有办法从 PowerShell 获取当前目录?我可以使用 GetVariableValue("pwd") 使用 PSCmdlet 来做到这一点。但是在 Cmd class 我没有那个可用。

Environment.CurrentDiretory 将我指向 powershell 的启动路径,而不是 PowerShell 本身当前所在的路径。

编辑

示例:

我通过 - 说 - powershell_ise.exe 启动了 powershell。它在 C:\Windows\System32\WindowsPowerShell\v1.0 后启动。然后我使用 cd c:\my\folder 和 运行 我的命令 Do-Something 更改路径。在 "Do-Something"(C# 端)的实现中,我希望能够检索当前路径 => c:\my\folder.

如果可能,我想避免使用 PSCmdlet

我从 C:\Users\<myusername> 开始。如果我知道输入 cd.. 我在 C:\Users\

正在输入 (Get-Location).Path returns C:\Users。这就是你想要的,不是吗?

或者试试:

WriteObject(this.SessionState.Path.CurrentFileSystemLocation);

参考:How can I get the current directory in PowerShell cmdlet?