我正在编写一个 PowerShell Cmdlet 并使用WriteDebug,但我想编写一个需要额外 API 调用的对象,我宁愿在调试关闭时不进行该调用。如何检测是否设置了 Debug 标志,以便我可以完全跳过对 WriteDebug 的调用?
例如,我的 WriteDebug 调用将如下所示:
WriteDebug(string.Format("Name : {0}", api.GetName(myobj)));
Run Code Online (Sandbox Code Playgroud)
在那个例子中,我想避免调用api.GetName除非打开调试。
只需检查 -Debug 标志是否设置可以使用下面的代码完成,但这还不够。
bool debug = false;
bool containsDebug = MyInvocation.BoundParameters.ContainsKey("Debug");
if (containsDebug)
debug = ((SwitchParameter)MyInvocation.BoundParameters["Debug"]).ToBool();
Run Code Online (Sandbox Code Playgroud)
PowerShell 还允许您设置一个名为 $DebugPreference 的全局标志,上面的代码不会检查该标志。从另一个 cmdlet 调用一个 cmdlet 会继承这些通用参数,这些参数不是通过上述代码检查的 Debug 标志继承的。下面的代码将检查 $DebugPreference 并解决这些问题。
debug = (ActionPreference)GetVariableValue("DebugPreference") != ActionPreference.SilentlyContinue;
Run Code Online (Sandbox Code Playgroud)
不幸的是,与 PowerShell 中的 cmdlet 相反,您必须同时检查两者。所以最终的C#代码如下。我还添加了 Verbose 通用参数的代码作为奖励。请务必从 PSCmdlet 而不是 Cmdlet 继承以获取 GetVariableValue 方法。
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;
Run Code Online (Sandbox Code Playgroud)
尝试这个:
$Debug = $psboundparameters.debug.ispresent
if ($Debug){
Write-Debug(string.Format("Name : {0}", api.GetName(myobj))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2537 次 |
| 最近记录: |