12

I have a custom C# PowerShell Cmdlet (inheriting from the Cmdlet base class) and I want to be able to identify if the "-Verbose" parameter was specified when running the Cmdlet. I realize that WriteVerbose will output when the -Verbose parameter is specified, but I would like to actually do some other code when -Verbose is specified (i.e. not output the Console.Write values when -Verbose is specified).

Thanks,

John

John Chapman
  • 878
  • 3
  • 14
  • 28

2 Answers2

10

Check the cmdlet's bound parameters like so:

if (this.MyInvocation.BoundParameters.ContainsKey("Verbose"))
{
}
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • MyInvocation is not a member of the "this" (Cmdlet) object. The class inherits from System.Management.Automation.Cmdlet. – John Chapman Oct 01 '12 at 20:08
  • 1
    Is there a reason not to inherit from PSCmdlet? – Keith Hill Oct 01 '12 at 20:52
  • 2
    You pretty much have to inherit from PSCmdlet to get at the bound parameters. Also note that Verbose will be in the bound parameters even if it has been specified as -Verbose:false, so ideally you need to check the value of the parameter too. – StephenD Oct 02 '12 at 07:00
  • PSCmdlet is located here: System.Management.Automation.PSCmdlet, just inheriting from Cmdlet doesn't do it. – Omzig Aug 09 '21 at 15:17
0

After much digging about, this works for me. Visual Studio 2013, Powershell 3.0 C# cmdlet using the PsCmdlet namespace. import-module .\mytest.dll, then mytest -verbose

blnVerbose = this.MyInvocation.Line.ToLower().Contains("-verbose");
Bruce Gavin
  • 349
  • 3
  • 9