在Cmdlet中,如何检测是否设置了Debug标志? [英] In a Cmdlet, how can I detect if the Debug flag is set?
问题描述
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 turned off. How can I detect whether the Debug flag is set or not, so that I can skip this call to WriteDebug entirely?
例如,我的WriteDebug调用将如下所示:
For example, my WriteDebug call will look something like this:
WriteDebug(string.Format("Name : {0}", api.GetName(myobj)));
在该示例中,除非调试已打开,否则我想避免调用 api.GetName
.
In that example, I want to avoid the call to api.GetName
unless debugging is turned on.
推荐答案
仅通过以下代码检查是否已设置-Debug标志,但这还不够.
Just checking if the -Debug flag is set can be done with the code below, but it is not enough.
bool debug = false;
bool containsDebug = MyInvocation.BoundParameters.ContainsKey("Debug");
if (containsDebug)
debug = ((SwitchParameter)MyInvocation.BoundParameters["Debug"]).ToBool();
PowerShell还允许您设置一个名为$ DebugPreference的全局标志,上面的代码不会检查该标志.从另一个cmdlet调用一个cmdlet会继承这些通用参数,而上述代码不会通过Debug标志继承这些参数.下面的代码将检查$ DebugPreference并解决这些问题.
PowerShell also allows you to set a global flag called $DebugPreference which the code above does not check. And calling a cmdlet from another cmdlet inherits these common parameters which is not inherited through the Debug flag as the code above checks. The code below will check $DebugPreference and solves those problems.
debug = (ActionPreference)GetVariableValue("DebugPreference") != ActionPreference.SilentlyContinue;
Unfortunately in contrary to a cmdlet in PowerShell you have to check both. So the final C# code is as below. I have also added the code for the Verbose common parameter as bonus. Be sure to inherit from PSCmdlet instead of Cmdlet to get to the GetVariableValue method.
bool debug = false;
bool containsDebug = MyInvocation.BoundParameters.ContainsKey("Debug");
if (containsDebug)
debug = ((SwitchParameter)MyInvocation.BoundParameters["Debug"]).ToBool();
else
debug = (ActionPreference)GetVariableValue("DebugPreference") != ActionPreference.SilentlyContinue;
bool verbose = false;
bool containsVerbose = MyInvocation.BoundParameters.ContainsKey("Verbose");
if (containsVerbose)
verbose = ((SwitchParameter)MyInvocation.BoundParameters["Verbose"]).ToBool();
else
verbose = (ActionPreference)GetVariableValue("VerbosePreference") != ActionPreference.SilentlyContinue;
这篇关于在Cmdlet中,如何检测是否设置了Debug标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!