17

For things like -WhatIf, we have $PSCmdlet.ShouldProcess() given to us by the [CmdletBinding] attribute. Are there other such tools or practices for implementing common command line arguments such as -Verbose, -Debug, -PassThru, etc?

bwerks
  • 8,651
  • 14
  • 68
  • 100

1 Answers1

16

Write-Debug and Write-Verbose handle the -Debug and -Verbose parameters automatically.

-PassThru isn't technically a common parameter, but you can implement it like:

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

1..10|PassTest -PassThru

And this is an example of using your function's PassThru value on a cmdlet:

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

Have a look at Get-Help about_CommonParameters for more information.

Rynant
  • 23,153
  • 5
  • 57
  • 71
  • I think you may want to store the input variable, do something then passthru the stored variable at the end (if $passthru). – Matt Aug 04 '11 at 05:15
  • 2
    Yes, 'PassTest` is not a useful function; just a trivial example to illustrate how `-PassThru` can be implemented. Plus, it's also possible that you might do something with the input variable, but passthru the original value unchanged (ex. `$_.Kill();if($PassThru){$_}`). I've added a non-trival example of using the PassThru parameter to set the PassThru of another command. – Rynant Aug 04 '11 at 12:54