Powershell to C# - Get-WMIObject

本文关键字:Get-WMIObject to Powershell | 更新日期: 2023-09-27 18:27:56

所以这里是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,但我如何访问请求中的数据?(这是选择对象用户、应用程序、请求GUID)

Powershell to C# - Get-WMIObject

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

foreach (dynamic result in results)
{
    var msg = String.Format{"User: {0}, Application: {1}, RequestGUID: {2}", 
                            result.User, result.Application, result.RequestGUID);
    MessageBox.Show(msg);
}

为了获取由Select-Object cmdlet创建的自定义对象,您可以迭代Properties成员:

foreach (var result in results)
{
    foreach ( var property in result.Properties )
    {
        MessageBox.Show( string.Format( "name: {0} | value: {1}", property.Name, property.Value ) );
    }
}