3

所以这里是powershell:

$app = Get-WmiObject -Class SMS_UserApplicationRequest -Namespace root/SMS/site_sitename -
 ComputerName computername | Select-Object User, Application, RequestGUID

$app

它工作正常,返回信息没有问题。

在 C# 中运行:

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

PowerShell powerShell = PowerShell.Create();
powerShell.Runspace = runspace;
powerShell.AddScript(script);

Collection<PSObject> results = powerShell.Invoke();

foreach (PSObject result in results)
{
    MessageBox.Show(result.ToString());
}

runspace.Close();

这显示了baseObject,即UserApplicationRequest,但是如何访问请求中的数据呢?(那是 Select-Object User, Application, RequestGUID)

4

2 回答 2

1

如果您使用的是 PowerShell V3 (System.Management.Automation.dll 3.0),请不要忘记它现在位于 DLR 上。这意味着 PSObject 可以通过dynamicC# 中的关键字使用,例如:

foreach (dynamic result in results)
{
    var msg = String.Format{"User: {0}, Application: {1}, RequestGUID: {2}", 
                            result.User, result.Application, result.RequestGUID);
    MessageBox.Show(msg);
}
于 2013-08-17T20:29:27.303 回答
1

为了获取由Select-Objectcmdlet 创建的自定义对象,您可以遍历该Properties成员:

foreach (var result in results)
{
    foreach ( var property in result.Properties )
    {
        MessageBox.Show( string.Format( "name: {0} | value: {1}", property.Name, property.Value ) );
    }
}
于 2013-08-16T20:50:14.813 回答