How to capture a Powershell CmdLet's verbose output when the CmdLet is programmatically Invoked from C#

后端 未结 2 2112
花落未央
花落未央 2021-02-14 22:33

BACKGROUND

  • I am using Powershell 2.0 on Windows 7.
  • I am writing a cmdlet in a Powershell module (\"module\" is new to Powershell 2.0).
  • To test
相关标签:
2条回答
  • 2021-02-14 22:39
    • Verbose output is not actually output unless $VerbosePreference is set at least to "Continue."
    • Use the PowerShell type to run your cmdlet, and read VerboseRecord instances from the Streams.Verbose propery

    Example in powershell script:

    ps> $ps = [powershell]::create()
    ps> $ps.Commands.AddScript("`$verbosepreference='continue'; write-verbose 42")
    ps> $ps.invoke()
    ps> $ps.streams.verbose
    Message   InvocationInfo                          PipelineIterationInfo
    -------   --------------                          ---------------------
    42        System.Management.Automation.Invocat... {0, 0}
    

    This should be easy to translate into C#.

    0 讨论(0)
  • 1.        string scriptFile = "Test.ps1";
    2.        using (PowerShell ps = PowerShell.Create())
    3.        {
    4.          const string getverbose = "$verbosepreference='continue'"; 
    5.          ps.AddScript(string.Format(getverbose));
    6.          ps.Invoke();
    7.          ps.Commands.Clear();
    8.          ps.AddScript(@".\" + scriptFile);
    9.          ps.Invoke();
    10.         foreach (var v in ps.Streams.Verbose)
    11.         {
    12.               Console.WriteLine(v.Message);
    13.         }
    14.       }
    

    Important lines are line 5 and 6. This basically set the $verbosepreference for the session and for upcoming new commands and scripts.

    0 讨论(0)
提交回复
热议问题