如何在C#中管道Powershell命令 [英] How pipe powershell commands in c#

查看:191
本文介绍了如何在C#中管道Powershell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是获取Exchange 2010站点的最小数据库,因此我试图从c#运行以下powershell命令,

The goal is get the smallest database of an Exchange 2010 site, so I'm trying to run the following powershell command from c#,

Get-MailboxDatabase -server Exchange2010 -Status | select-object Name,DatabaseSize

我苦苦挣扎的问题是-如何通过Select子句命令传递管道.

The problem I'm struggling is - how pipe the Select clause command.

这是我的尝试,

WSManConnectionInfo wsConnectionInfo = new WSManConnectionInfo(new Uri("https://" + ExchangeSite + "/powershell?serializationLevel=Full"),
    "http://schemas.microsoft.com/powershell/Microsoft.Exchange", getCredential());
wsConnectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
wsConnectionInfo.SkipCACheck = true;
wsConnectionInfo.SkipCNCheck = true;

rsRemoteRunspace = RunspaceFactory.CreateRunspace(wsConnectionInfo);
rsRemoteRunspace.Open();
Pipeline pipeLine = rsRemoteRunspace.CreatePipeline();

Collection<PSObject> DatabaSize = null;

Command myCommand = new Command("Get-MailboxDatabase");
myCommand.Parameters.Add("Server", "Exchange2010");
myCommand.Parameters.Add("Status", null);
Command myCommand2 = new Command("Select-Object");
    myCommand.Parameters.Add("Name");
myCommand.Parameters.Add("DatabaseSize");
pipeLineMB.Commands.Add(myCommand);
pipeLineMB.Commands.Add(myCommand2);
DatabaSize = pipeLine.Invoke();

但是我得到了,

"A parameter cannot be found that matches parameter name 'Name'."

请记住,我不能使用SnapIn,因为代码必须在运行Exchange服务器上的cmdlet的客户端计算机上运行.

Please keep in mind I cannot use SnapIn because the code must run on a client machine that executes cmdlets on the Exchange server.

欢迎任何建议.

编辑

我应用了yamen建议的修复程序,并且能够调用该命令,但是当我尝试获取该值时,我得到:对象引用未设置为对象的实例."

I applied the fix suggested by yamen and the command was able to be invoked but when I try to get the value, I get: "Object reference not set to an instance of an object."

请注意,我可以获取Servername和Name的值,但它在DatabaseSize中失败,因此我猜想'Status'标志未正确设置,因为该标志是启用该值的标志.

Notice that I can get the values of Servername and Name but it fails in the DatabaseSize so I guess the 'Status' flag is not being set properly because this flag is the one which enables this value.

推荐答案

您的意思是:

Command myCommand2 = new Command("Select-Object");
myCommand2.Parameters.Add("DatabaseSize");

代替此:

Command myCommand2 = new Command("Select-Object");
myCommand.Parameters.Add("DatabaseSize");

在第二行显示myCommand2通知吗?

无论如何,您可能会发现实际上要使用的参数是Property viz:

Regardless, you might find that the parameter you're actually after is Property viz:

myCommand2.Parameters.Add("Property", "DatabaseSize");

而且不止一个:

var props = new string[] { "DatabaseSize", "ServerName", "Name" };
myCommand2.Parameters.Add("Property", props);

这篇关于如何在C#中管道Powershell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆