从.NET调用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(); } 

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

由于您提供的是运行Runspace ,因此您需要做的就是在SessionStateProxy上设置Path属性:

 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(); } 

提前设置System.Environment.CurrentDirectory会做你想要的。

您应该打开 Runspace 之前随时设置System.Environment.CurrentDirectory ,而不是将Set-Location添加到您的脚本中。 它将inheritanceCurrentDirectory打开时的内容:

 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(); } 

请记住, Set-Location不设置.net框架的CurrentDirectory因此如果您调用的是工作在“当前”位置的.Net方法,则需要自己设置。

这样做有什么不妥:

 pipeline.Commands.AddScript(@"set-location c:\scripts;.\foo.ps1") 

-Oisin

您可以使用以下命令在powershell中设置工作目录

 set-location c:\mydirectory 

您还可以尝试PowerShell启动脚本($ profile)。 C:…. \ MyDocs \ WindowsPowerShell \ Microsoft.PowerShell_profile.ps1但仅当此目录已修复且未更改时