In a Cmdlet, how can I detect if the Debug flag is set?

前端 未结 4 457
暗喜
暗喜 2020-12-19 13:09

I\'m writing a PowerShell Cmdlet and using WriteDebug, but I want to write an object which requires an extra API call, and I\'d rather not make that call when debugging is t

4条回答
  •  被撕碎了的回忆
    2020-12-19 13:42

    To access the Debug flag from C# you should be able to do essentially the same thing as mjolinor suggests:

    if (this.MyInvocation.BoundParameters.ContainsKey("Debug"))
    {
        ... do something ...
    }
    

    However, note that you can specify the debug parameter with a value of false:

    MyCmdlet -Debug:$false
    

    To handle this case, you probably want to add something like this (from within the PSCmdlet):

    bool debug = MyInvocation.BoundParameters.ContainsKey("Debug") &&
                 ((SwitchParameter)MyInvocation.BoundParameters["Debug"]).ToBool();
    

    In C# BoundParameters is a dictionary, so you could also use TryGetValue(), but note that the value of a switch (like Debug) is a SwitchParameter not a bool.

    for further information see the following:

    • PSCmdlet.MyInvocation: http://msdn.microsoft.com/en-us/library/system.management.automation.pscmdlet.myinvocation(v=vs.85).aspx
    • BoundParameters: http://msdn.microsoft.com/en-us/library/system.management.automation.invocationinfo.boundparameters(v=vs.85).aspx
    • SwitchParameter: http://msdn.microsoft.com/en-us/library/windows/desktop/system.management.automation.switchparameter(v=vs.85).aspx

提交回复
热议问题