2

I have this simple program using powershell. This is just a proof of concept, I'm using the same code in a larger app. The problem is that the values of some of the properties in the code below can't be read. Reading the Value property throws a GetValueInvocationException.

This actually even happens with one of Microsoft sample projects that comes with the PowerShell SDK. Why is this and is there a solution?

static void Main(string[] args)
    {
        var powerShell = System.Management.Automation.PowerShell.Create();

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

        powerShell.Runspace = runspace;
        powerShell.AddScript("Get-Process");
        var results = powerShell.Invoke();

        foreach (var prop in results.First().Properties)
        {
            try
            {
                Console.WriteLine(prop.Name + " : " + prop.Value);
            }
            catch (Exception e)
            {
                Console.WriteLine(string.Format("Exception {0} on {1}", e.GetType(), prop.Name));
            }
        }

        Console.ReadKey();
    }

1 Answer 1

2

This is either by design (after all, it a target object property getter throws) or an issue (if this effect is not intentional in PowerShell). In both cases we cannot do much about this now. That is, we should use the try/catch approach in such vcases. One option we have is to submit the report to: https://connect.microsoft.com/PowerShell/Feedback

Try to get the target object in your C# code (it is System.Diagnostics.Process, get it via BaseObject property of a result object) and access that culprit property. It will throw, more likely, as well.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah you're probably right. I should just ignore those properties. The thing is that I am doing this generally and don't really know in code what the BaseObject is. What I did before (and wanted to change) was using the PowerShell Job API. Then I had no such problems. But when I look at the properties returned I see that that the properties throwing exceptions in my example is not available when using the Job approach. So I guess try/catch is the way to go. Thanks :)
Yes, try/catch is what I do in my custom host when it deals with unknown objects (read, objects which property getters may throw).

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.