[英]PowerShell cmd in c# call Invoke return no PsObject for specific user email list
我尝试通过c#使用此PowerShell命令获取Exchange服务器中特定用户的电子邮件列表
"get-mailbox -Identity username -resultsize unlimited | select Name -expand EmailAddresses | Select SmtpAddress"
在Powershell控制台中进行这项工作
但是,如果我在PowerShell上调用Invoke ,则不会返回PsObject,有没有办法解决这个问题?
我尝试仅将此脚本称为"get-mailbox -Identity user"
但得到了PSObject,但我必须这样做
Collection<PSObject> getInfo = new Collection<PSObject>();
getInfo = runExchCmd(Pscmd); // runExchCmd just a function to invoke PowerShellCommand to be execute and return Collection PSObject
PSMemberInfo psobjEmail = getInfo[0].Members["EmailAddresses"];
object obj = psobjEmail.Value;
但是是的,它的值是一个很长的字符串,所有电子邮件都与用户相关联,只是将每封电子邮件提取到数组中有任何帮助似乎很痛苦?
以我的经验,在C#中运行Powershell和Microsoft Exchange代码可能会有些棘手。 这是我必须要做的:
在您的App.Config
的添加useLegacyV2RuntimeActivationPolicy="true"
到像这样的启动标签(你不必有.NET 4.5)这使得Microsoft.Exchange.Management.PowerShell.Admin正确加载(你必须有安装在本地计算机上运行的Exchange工具)。:
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
然后,假设您已将System.Management.Automation
引用添加到您的项目中,则可以像在C#中那样构造Powershell查询:
string username = "username";
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("param ([string]$user); add-pssnapin 'Microsoft.Exchange.Management.PowerShell.Admin';" +
"get-mailbox -Identity $user -resultsize unlimited | select Name -expand EmailAddresses | Select SmtpAddress;");
PowerShellInstance.AddParameter("user", username);
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
if (PowerShellInstance.Streams.Error.Count > 0)
{
foreach (var error in PowerShellInstance.Streams.Error)
{
//for reading errors in debug mode
StringBuilder sb = new StringBuilder();
sb.AppendLine(error.Exception.Message);
sb.AppendLine(error.Exception.InnerException.Message);
sb.AppendLine(error.CategoryInfo.Category.ToString());
sb.AppendLine(error.CategoryInfo.Reason);
sb.AppendLine(error.ErrorDetails.Message);
sb.AppendLine(error.ErrorDetails.RecommendedAction);
Console.WriteLine(sb.ToString());
}
}
if (PSOutput.Count > 0)
{
foreach (var item in PSOutput)
{
Console.WriteLine(item);
}
}
}
我还必须更改项目以将其构建为x64,因为Exchange的Powershell插件是64位的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.