我有一个带有静态方法的DLL,想知道当前目录。我加载了库
c:\temp> add-type -path "..."
...并调用方法
c:\temp> [MyNamespace.MyClass]::MyMethod()
但是Directory.GetCurrentDirectory()
和。Environment.CurrentDirectory
都会使当前目录错误...
这样做的正确方法是什么?
答案 0 :(得分:5)
PowerShell中有两个可能的“目录”。一个是流程的当前目录,可通过Environment.CurrentDirectory
或Directory.GetCurrentDirectory()
获取。另一个“目录”是当前Powershell Provider中的当前位置。这是您在命令行中看到的内容,可通过get-location
cmdlet获得。当您使用set-location
(别名cd)时,您正在更改此内部路径,而不是进程的当前目录。
如果你想要一些使用进程当前目录的.NET库来获取当前位置,那么你需要明确地设置它:
[Environment]::CurrentDirectory = get-location
Powershell有一个可扩展的模型,允许像文件系统中的驱动器一样安装不同的数据源。文件系统只是众多提供商之一。您可以通过get-psprovider
查看其他提供商。例如,注册表提供程序允许Windows注册表像文件系统一样进行导航。另一个“功能”可让您通过dir function:
查看所有功能。
答案 1 :(得分:1)
如果DLL中的命令继承自System.Management.Automation.PSCmdLet
,则当前PS位置在SessionState.Path
中可用。
public class SomeCommand : PSCmdlet
{
protected override void BeginProcessing()
{
string currentDir = this.SessionState.Path.CurrentLocation.Path;
}
}
要获得没有会话引用的路径,此代码似乎有效。我在遍历了使GIT在PS GIT Completions(特别是this function here)中自动完成的代码后找到了这个解决方案。
public class Test
{
public static IEnumerable<string> GetPath()
{
using (var ps = PowerShell.Create(RunspaceMode.CurrentRunspace))
{
ps.AddScript("pwd");
var path = ps.Invoke<PathInfo>();
return path.Select(p => p.Path);
}
}
}
输出:
PS C:\some\folder> [Test]::GetPath()
C:\some\folder