所以这是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)
答案 0 :(得分:1)
为了获取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 ) );
}
}
答案 1 :(得分:1)
如果您使用的是PowerShell V3(System.Management.Automation.dll 3.0),请不要忘记它现在位于DLR上。这意味着可以通过C#中的dynamic
关键字来使用PSObject:
foreach (dynamic result in results)
{
var msg = String.Format{"User: {0}, Application: {1}, RequestGUID: {2}",
result.User, result.Application, result.RequestGUID);
MessageBox.Show(msg);
}