[英]How can I set the runspace of PowerShell code I am running from c#?
I have an app which runs several Powershell scripts. 我有一个运行几个Powershell脚本的应用程序。 (It is basically a wrapper application that pulls some PS scripts stored in a SQL database and then runs them.)
(基本上,这是一个包装器应用程序,可以提取存储在SQL数据库中的一些PS脚本,然后运行它们。)
One of the Powershell scripts I have added is failing now, and I have a feeling it is because it needs to run in the STA apartment state. 我添加的Powershell脚本之一现在失败了,我感觉是因为它需要在STA公寓状态下运行。 However, I don't know how to set the apartmentstate in c#.
但是,我不知道如何在C#中设置apartmentstate。
The function I am using is as follows: 我正在使用的功能如下:
public bool RunSomePowershell(string script)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(script);
var result = PowerShellInstance.Invoke();
return Convert.ToBoolean(result[result.Count -1].ToString()); // Result should be last output from script (true or false)
}
}
How can I set this to run the scripts in STA mode? 如何设置它以STA模式运行脚本?
First, create a runspace and set the ApartmentState
property: 首先,创建一个运行空间并设置
ApartmentState
属性:
using System.Threading;
using System.Management.Automation.Runspaces;
// ...
Runspace rs = RunspaceFactory.CreateRunspace();
rs.ApartmentState = ApartmentState.STA;
Then set the Runspace
property of the PowerShell
instance to use the aforementioned runspace: 然后将
PowerShell
实例的Runspace
属性设置为使用上述运行空间:
PowerShellInstance.Runspace = rs;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.