Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell to C# - Get-WMIObject

Tags:

c#

powershell

So here's the powershell:

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

$app

It works fine, returns the info with no problem.

Running in 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();

This shows the baseObject, which is the UserApplicationRequest, but how do I access the data in the request? (That was the Select-Object User, Application, RequestGUID)

like image 289
ctd25 Avatar asked May 11 '26 03:05

ctd25


1 Answers

If you are on PowerShell V3 (System.Management.Automation.dll 3.0), don't forget that it is now sitting on the DLR. That means that PSObject can be used via the dynamic keyword in C# e.g.:

foreach (dynamic result in results)
{
    var msg = String.Format{"User: {0}, Application: {1}, RequestGUID: {2}", 
                            result.User, result.Application, result.RequestGUID);
    MessageBox.Show(msg);
}
like image 124
Keith Hill Avatar answered May 12 '26 15:05

Keith Hill