C# .Net程序集在PowerShell 2运行空间中不工作

C# .Net程序集在PowerShell 2运行空间中不工作,c#,.net,powershell,C#,.net,Powershell,我通过Runspace和Pipeline从c#运行powershell脚本 我需要支持Powershell 2 我的脚本使用[System.Net.WebRequest] 在这台机器上的PS CLI中,[System.Net.WebRequest]工作正常 但是,从c#运行脚本会导致 Unable to find type [System.Net.WebRequest]: make sure that the assembly containing this type is loaded. 我

我通过
Runspace
Pipeline
从c#运行powershell脚本

我需要支持Powershell 2

我的脚本使用
[System.Net.WebRequest]

在这台机器上的PS CLI中,
[System.Net.WebRequest]
工作正常

但是,从c#运行脚本会导致

Unable to find type [System.Net.WebRequest]: make sure that the assembly containing this type is loaded.
我尝试使用
Add Type
加载
System.Net
,并确认它已加载
[appdomain]::CurrentDomain.getAssemblys()

但错误依然存在

如果计算机具有PS 3.0,则没有问题

编辑:完整的相关代码

InitialSessionState initial = InitialSessionState.CreateDefault();
runspace = RunspaceFactory.CreateRunspace(initial);
runspace.ApartmentState = System.Threading.ApartmentState.STA;
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline()) {
  pipeline.Commands.AddScript(scriptText);
  <invoke, read output etc>
}
InitialSessionState initial=InitialSessionState.CreateDefault();
runspace=RunspaceFactory.CreateRunspace(初始值);
runspace.ApartmentState=System.Threading.ApartmentState.STA;
Open();
使用(Pipeline Pipeline=runspace.CreatePipeline()){
pipeline.Commands.AddScript(scriptText);
}

我创建了一个测试应用程序,发现这不是问题

这个问题只发生在我的主应用程序中

在缩小差异几个小时后,我发现我可以通过加载并使用我的共享模块在我的测试应用程序中重新创建问题

我把它缩小到共享DLL模块中的共享
GetMyVersion
例程

Assembly assembly = Assembly.GetExecutingAssembly();
return FileVersionInfo.GetVersionInfo(assembly.Location);
解决方案是在exe中尽早执行此代码。我可以在应用程序的其余部分保留共享DLL例程的常规用法

另一种可能更可靠并且在其他情况下也有帮助的解决方案是直接访问程序集

$sysManagement = [System.Reflection.Assembly]::LoadWithPartialName("System.Net");
$netType = $sysManagement.GetType("System.Net.WebRequest",$true);
$netType::Create("http://etc.com")

可能是在MTA中运行(PS 2的默认设置)引起的。确保您的运行空间在单线程单元(STA)中运行—不会有好运。通过
[System.Threading.Thread]确认:CurrentThread.GetApartmentState()