Capturing Powershell output in C# after Pipeline.Invoke throws

前端 未结 3 621
时光说笑
时光说笑 2020-12-03 15:14

I\'m running a Powershell test script from a C# application. The script can fail due to a bad cmdlet which causes pipe.Invoke() to throw an exception.

I\'m able to c

3条回答
  •  旧巷少年郎
    2020-12-03 15:37

    The solution I ended up using was to implement our own PSHost to handle PowerShell's output. The initial information for this came from http://community.bartdesmet.net/blogs/bart/archive/2008/07/06/windows-powershell-through-ironruby-writing-a-custom-pshost.aspx in the "Building a custom PS host" section.

    In my case it did require using a custom PSHostRawUserInterface as well.

    Here's the quick overview of what was done. I've only listed the function I actually implimented, but there's many that are just contain throw new NotImplementedException();

    private class myPSHost : PSHost
    {
       (Same as what the above link mentions)
    }
    private class myPSHostUI : PSHostUserInterface
    {
       private myPSHostRawUI rawui = new myPSHostRawUI();
    
       public override void Write // all variations
       public override PSHostRawUserInterface RawUI { get { return rawui; } }
    
    }
    private class myPSHostRawUI : PSHostRawUserInterface
    {
       public override ConsoleColor ForegroundColor
       public override ConsoleColor BackgroundColor
       public override Size BufferSize
    }
    

提交回复
热议问题