如何在自定义 cmdlet 中正确使用 -verbose 和 -debug 参数 [英] How to properly use the -verbose and -debug parameters in a custom cmdlet
问题描述
默认情况下,任何具有 [CmdletBinding()] 属性的命名函数都接受 -debug
和 -verbose
(以及其他一些)参数并具有预定义的$debug
和 $verbose
变量.我想弄清楚如何将它们传递给在函数内调用的其他 cmdlet.
By default, any named function that has the [CmdletBinding()] attribute accepts the -debug
and -verbose
(and a few others) parameters and has the predefined $debug
and $verbose
variables. I'm trying to figure out how to pass them on to other cmdlet's that get called within the function.
假设我有一个这样的 cmdlet:
Let's say I have a cmdlet like this:
function DoStuff() {
[CmdletBinding()]
PROCESS {
new-item Test -type Directory
}
}
如果 -debug
或 -verbose
被传递到我的函数中,我想将该标志传递到 new-item
cmdlet.这样做的正确模式是什么?
If -debug
or -verbose
was passed into my function, I want to pass that flag into the new-item
cmdlet. What's the right pattern for doing this?
推荐答案
也许这听起来很奇怪,但没有任何简单的方法让 cmdlet 知道其详细或调试模式.看一下相关问题:
Perhaps it sounds strange, but there isn't any easy way for a cmdlet to know its verbose or debug mode. Take a look at the related question:
cmdlet 的作用知道什么时候真正应该调用 WriteVerbose() 吗?
一个不完美但实际上合理的选项是引入您自己的 cmdlet 参数(例如,$MyVerbose
和 $MyDebug
)并在代码中明确使用它们:
One not perfect, but practically reasonable, option is to introduce your own cmdlet parameters (for example, $MyVerbose
and $MyDebug
) and use them in the code explicitly:
function DoStuff {
[CmdletBinding()]
param
(
# Unfortunately, we cannot use Verbose name with CmdletBinding
[switch]$MyVerbose
)
process {
if ($MyVerbose) {
# Do verbose stuff
}
# Pass $MyVerbose in the cmdlet explicitly
New-Item Test -Type Directory -Verbose:$MyVerbose
}
}
DoStuff -MyVerbose
更新
当我们只需要一个开关(而不是详细级别值)时,使用 $PSBoundParameters
的方法可能比本答案第一部分中提出的更好(带有额外参数):
When we need only a switch (not, say, a verbosity level value) then the approach with $PSBoundParameters
is perhaps better than proposed in the first part of this answer (with extra parameters):
function DoStuff {
[CmdletBinding()]
param()
process {
if ($PSBoundParameters['Verbose']) {
# Do verbose stuff
}
New-Item Test -Type Directory -Verbose:($PSBoundParameters['Verbose'] -eq $true)
}
}
DoStuff -Verbose
无论如何,这一切都不完美.如果有更好的解决方案,那么我真的很想亲自了解它们.
It's all not perfect anyway. If there are better solutions then I would really like to know them myself.
这篇关于如何在自定义 cmdlet 中正确使用 -verbose 和 -debug 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!