从.NET调用Powershell时设置start dir?

Ric*_*all 15 c# powershell

我正在使用System.Management.Automation API来调用PowerShell脚本C#WPF应用程序.在下面的示例中,您将如何更改起始目录($ PWD),以便它从C:\ scripts \执行foo.ps1而不是从它调用的.exe的位置?

using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
    runspace.Open();
    using (Pipeline pipeline = runspace.CreatePipeline())
    {
        pipeline.Commands.Add(@"C:\scripts\foo.ps1");
        pipeline.Invoke();
    }
    runspace.Close();
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*ley 10

您无需更改System.Environment.CurrentDirectory以更改PowerShell脚本的工作路径.这样做可能非常危险,因为如果您正在运行对当前目录敏感的其他代码,则可能会产生无意的副作用.

由于您提供的是Runspace,您需要做的就是在以下位置设置Path属性SessionStateProxy:

using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
    runspace.Open();
    runspace.SessionStateProxy.Path.SetLocation(directory);
    using (Pipeline pipeline = runspace.CreatePipeline())
    {
        pipeline.Commands.Add(@"C:\scripts\foo.ps1");
        pipeline.Invoke();
    }
    runspace.Close();
}
Run Code Online (Sandbox Code Playgroud)


Jay*_*kul 7

System.Environment.CurrentDirectory提前设定将做你想要的.

Set-Location您应该打开 Runspace 之前设置System.Environment.CurrentDirectory 任何时间,而不是添加到您的脚本.它将继承CurrentDirectory打开时的内容:

using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
    System.Environment.CurrentDirectory = "C:\\scripts";
    runspace.Open();
    using (Pipeline pipeline = runspace.CreatePipeline())
    {
        pipeline.Commands.Add(@".\foo.ps1");
        pipeline.Invoke();
    }
    runspace.Close();
}
Run Code Online (Sandbox Code Playgroud)

请记住,Set-Location不设置.net框架,CurrentDirectory所以如果你调用的是工作在"当前"位置的.Net方法,你需要自己设置它.