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

后端 未结 2 2106
花落未央
花落未央 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#.

提交回复
热议问题