开发者

Enumerating PowerShell object's properties throws

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 a开发者_如何学运维ctually 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();
    }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜