从 .NET 调用 Powershell 时设置启动目录? [英] Setting the start dir when calling Powershell from .NET?
问题描述
我正在使用 System.Management.Automation API 将 PowerShell 脚本调用为 C# WPF 应用程序.在以下示例中,您将如何更改起始目录 ($PWD) 以使其从 C:\scripts\ 执行 foo.ps1 而不是调用它的 .exe 的位置?
I'm using the System.Management.Automation API to call PowerShell scripts a C# WPF app. In the following example, how would you change the start directory ($PWD) so it executes foo.ps1 from C:\scripts\ instead of the location of the .exe it was called from?
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 脚本的工作路径.这样做可能非常危险,因为如果您正在运行其他对当前目录敏感的代码,这可能会产生意外的副作用.
You don't need to change the System.Environment.CurrentDirectory
to change the working path for your PowerShell scripts. It can be quite dangerous to do this because this may have unintentional side effects if you're running other code that is sensitive to your current directory.
由于您提供了 Runspace
,您需要做的就是在 SessionStateProxy
上设置 Path
属性:
Since you're providing a Runspace
, all you need to do is set the Path
properties on the 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();
}
这篇关于从 .NET 调用 Powershell 时设置启动目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!