Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: how to implement standard switches?

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?

like image 518
bwerks Avatar asked Aug 03 '11 19:08

bwerks


1 Answers

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.

like image 194
Rynant Avatar answered Oct 07 '22 18:10

Rynant