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

后端 未结 2 1544
隐瞒了意图╮
隐瞒了意图╮ 2021-02-14 22:30

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:46

    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.

提交回复
热议问题