Debugging Powershell:如何实现标准交换机?

Debugging Powershell:如何实现标准交换机?,debugging,powershell,command-line-arguments,passthru,verbose,Debugging,Powershell,Command Line Arguments,Passthru,Verbose,对于-WhatIf之类的内容,我们有[CmdletBinding]属性提供给我们的$PSCmdlet.ShouldProcess()。是否有其他此类工具或实践用于实现常见的命令行参数,如-Verbose、-Debug、-PassThru等?Write Debug和Write Verbose自动处理-Debug和-Verbose参数 -PassThru在技术上不是一个通用参数,但您可以像以下那样实现它: function PassTest { param( [switch]

对于-WhatIf之类的内容,我们有[CmdletBinding]属性提供给我们的$PSCmdlet.ShouldProcess()。是否有其他此类工具或实践用于实现常见的命令行参数,如-Verbose、-Debug、-PassThru等?

Write Debug
Write Verbose
自动处理
-Debug
-Verbose
参数

-PassThru
在技术上不是一个通用参数,但您可以像以下那样实现它:

function PassTest {
    param(
        [switch] $PassThru
    )
    process {
        if($PassThru) {$_}
    }
}

1..10|PassTest -PassThru
这是在cmdlet上使用函数的PassThru值的示例:

function Add-ScriptProperty {
    param(
        [string] $Name,
        [ScriptBlock] $Value,
        [switch] $PassThru
    )
    process{
        # Use ":" to explicitly set the value on a switch parameter
        $_| Add-Member -MemberType ScriptProperty -Name $Name -Value $Value `
            -PassThru:$PassThru 
    }
}

$calc = Start-Process calc -PassThru|
        Add-ScriptProperty -Name SecondsOld `
            -Value {((Get-Date)-$this.StartTime).TotalSeconds} -PassThru
sleep 5
$calc.SecondsOld

查看
获取有关\u CommonParameters的帮助以获取更多信息。

我认为您可能需要存储输入变量,执行一些操作,然后在末尾传递存储的变量(如果$passthru)。是的,'PassTest'不是一个有用的函数;这只是一个简单的例子来说明如何实现
-PassThru
。另外,您也可能对输入变量执行某些操作,但传递原始值时保持不变(例如,
$\uu0.Kill();if($passthru){$\u0}
)。我添加了一个使用PassThru参数设置另一个命令的PassThru的非平凡示例。