将Powershell命令添加到管道中
本文关键字:管道 添加 Powershell 命令 | 更新日期: 2023-09-27 18:29:04
我正在尝试从2010 Exchange服务器获取较低的存储,该函数将在WCF容器中运行。
我面临的问题是,我无法在管道中运行多个PowerShell命令。
我尝试了以下操作(在此基础上,如何从c#调用带有"格式列表"answers"输出文件"管道的powershell命令?):
string strCommand = @"Get-MailboxDatabase -Status | select ServerName,Name,DatabaseSize | Sort-Object DatabaseSize";
string CommandLine = string.Format("&{{{0}}}", strCommand);
pipeLine.Commands.AddScript(CommandLine);
但我得到了:
未处理的异常:System.Management.Automation.RemoteException:在受限语言模式或Data节中不允许使用脚本块文字。
我也试过了,
Command getMailbox = new Command("Get-MailboxDatabase");
getMailbox.Parameters.Add("Status", null);
Command sort = new Command("Sort-Object");
pipeLine.Commands.Add(getMailbox);
pipeLine.Commands.Add(sort);
Collection<PSObject> commandResults = pipeLine.Invoke();
但不是运气:
未处理的异常:System.Management.Automation.RemoteException:术语"排序对象"未被识别为cmdlet 的名称
我想知道我是否应该使用多个管道(每个cmdlet一个管道),但我不确定。
听起来问题出在运行空间上。如果这是一台Exchange服务器,并且您正在Exchange提供的远程管理会话中运行该服务器,那么在该会话中唯一能做的就是运行Exchange cmdlet。Select Object和Sort Object cmdlet以及其他PowerShell语言元素根本无法使用。
考虑到排序对象是名为'的架构无法识别的命令http://schemas.microsoft.com/powershell/Microsoft.Exchange"然后我继续使用管理单元开发一个功能,它运行良好
注意,我使用的是第一个数据库,因为默认的排序模式是升序。此外,我想评论一下,如果你在Framework 4.0上编译,你会收到一条"Value不能为null错误消息",所以你必须更改为3.5。
请记住,WCF服务正在使用它,所以管理单元没有问题。如果你想在任何其他应用程序上使用它,比如基于控制台的应用程序,那么你应该在那台计算机上安装EMS 2010。
此函数基本上执行以下PowerShell命令,Get-MailboxDatabase-Status|Sort Object DatabaseSize
private static string getLowServerStoreDN_SnapIn(string ExchangeSite)
{
string strResult = string.Empty;
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);
Runspace runspace = RunspaceFactory.CreateRunspace(rsConfig);
try
{
runspace.Open();
Command getMailbox = new Command("Get-MailboxDatabase");
getMailbox.Parameters.Add(new CommandParameter("Status", null));
Command sort = new Command("Sort-Object");
sort.Parameters.Add("Property", "DatabaseSize");
Pipeline commandPipeLine = runspace.CreatePipeline();
commandPipeLine.Commands.Add(getMailbox);
commandPipeLine.Commands.Add(sort);
Collection<PSObject> getmailboxResults = commandPipeLine.Invoke();
if (getmailboxResults.Count > 0)
{
PSObject getMailboxResult = getmailboxResults[0];
strResult = getMailboxResult.Properties["Name"].Value.ToString();
//foreach (PSObject getMailboxResult in getmailboxResults)
//{
// strResult = getMailboxResult.Properties["Name"].Value.ToString();
//}
}
}
catch (ApplicationException e)
{
//Console.WriteLine(e.Message);
throw new FaultException("function getLowServerStoreDN_SnapIn(" + ExchangeSite + "): " + e.Message,
FaultCode.CreateReceiverFaultCode("BadExchangeServer", "http://example.com"));
}
return strResult;
}