How to capture a Powershell CmdLet's verbose output when the CmdLet is programmatically Invoked from C#
- Verbose output is not actually output unless
$VerbosePreference
is set at least to "Continue." - Use the PowerShell type to run your
cmdlet
, and readVerboseRecord
instances from theStreams.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.verboseMessage InvocationInfo PipelineIterationInfo------- -------------- ---------------------42 System.Management.Automation.Invocat... {0, 0}
This should be easy to translate into C#.
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.