3

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)

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This worked, thank you! Still pretty new to powershell and c# in general, so I appreciate the help.
I'm running into a new issue on this - it works without a problem on the PC I wrote the code on, but any other PC, I get an exception thrown when I try to access one of the properties: runtimebinderexception PSObject does not contain a definition for "PropertyName" Any ideas what would cause this/why it would only work on the PC I wrote the code on?
0

In order to get at the custom objects being created by the Select-Object cmdlet you can iterate over the Properties member:

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

4 Comments

Tried - I get: can't operate of variables of type PSObject because PSObject does not contain a public definition for 'GetEnumerator'
Shouldn't it be var property in result.Properties ?
@Mitul - It should! Sorry about that typo and I'll fix it up. :)
@ctd25 - Okay made a quick fix on a typo for the answer. Sorry about that. Think that should fix the problem you were seeing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.