2017-02-10 36 views
1

我试图获取出站队列中消息的计数。我正在使用C#与Powershell来实现这一点。 我使用下面的命令从MSMQ出队中获取消息计数时发出的问题

Get-MsmqOutgoingQueue | Format-Table -Property MessageCount 

越做越PowerShell命令提示符成功执行该命令。但是,当我尝试这从C#,它给以下异常:

The type initializer for 'Microsoft.Msmq.PowerShell.Commands.Utilities' threw an exception. 

下面是我用来执行此命令的C#代码:

string scriptTest = "Get-MsmqOutgoingQueue | Format-Table -Property MessageCount"; 
Runspace runspace = RunspaceFactory.CreateRunspace(); 
runspace.Open(); 
Pipeline pipeline = runspace.CreatePipeline(); 
pipeline.Commands.AddScript(scriptText); 
pipeline.Commands.Add("Out-String"); 
Collection<PSObject> results = pipeline.Invoke(); 
runspace.Close(); 
string s = ""; 
foreach (PSObject obj in results) 
{ 
    s = obj.ToString(); 
} 
Console.WriteLine(s); 

我通过给所有试图验证码许可但它给出了相同的例外。

+0

是否有InnerException? – stuartd

+0

检查了InnerException并发现异常:“混合模式程序集针对运行时版本”v2.0.50727“构建,无法在4.0运行时加载,无需其他配置信息”通过修改App.Config修复了它。 – Brijesh

回答

1

通过在启动标签中添加以下useLegacyV2RuntimeActivationPolicy修复了此问题。

<configuration> 
<startup useLegacyV2RuntimeActivationPolicy="true"> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/> 
</startup> 
</configuration>