如何在自定义cmdlet中正确使用-verbose和-debug参数 [英] How to properly use the -verbose and -debug parameters in a custom cmdlet

查看:206
本文介绍了如何在自定义cmdlet中正确使用-verbose和-debug参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,具有[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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆