Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom Powershell operator?

Is it possible to create a custom operator in Powershell? And, how would I do that? I've searched Google but nothing is coming up.

I'm referring to specifically an infix operator:

$ExampleList -contains "element"

I've created cmdlets (with Powershell and C#), modules, etc., so I just need the broad strokes.

like image 507
Sam Porch Avatar asked Apr 20 '15 20:04

Sam Porch


People also ask

What does %% mean in PowerShell?

% is an alias for the ForEach-Object cmdlet. An alias is just another name by which you can reference a cmdlet or function.

Which operator combination is valid in PowerShell?

Use assignment operators ( = , += , -= , *= , /= , %= ) to assign, change, or append values to variables. You can combine arithmetic operators with assignment to assign the result of the arithmetic operation to a variable.


2 Answers

You can create a prefix operator but not an in-fix or post-fix operator e.g.:

Set-Alias ?: Invoke-Ternary
function Invoke-Ternary {
param(
    [Parameter(Mandatory, Position=0)]
    [scriptblock]
    $Condition,

    [Parameter(Mandatory, Position=1)]
    [scriptblock]
    $TrueBlock,

    [Parameter(Mandatory, Position=2)]
    [scriptblock]
    $FalseBlock,

    [Parameter(ValueFromPipeline, ParameterSetName='InputObject')]
    [psobject]
    $InputObject
)

Process {
    if ($pscmdlet.ParameterSetName -eq 'InputObject') {
        Foreach-Object $Condition -input $InputObject | Foreach {
            if ($_) {
                Foreach-Object $TrueBlock -InputObject $InputObject
            }
            else {
                Foreach-Object $FalseBlock -InputObject $InputObject
            }
        }
    }
    elseif (&$Condition) {
        &$TrueBlock
    }
    else {
        &$FalseBlock
    }
}

Use like so:

$toolPath = ?: {[IntPtr]::Size -eq 4} {"$env:ProgramFiles(x86)\Tools"} {"$env:ProgramFiles\Tools"}}
like image 82
Keith Hill Avatar answered Sep 24 '22 17:09

Keith Hill


After thinking on it, this is what I came up with:

Not sure if it's a better answer than Jon Tirjan's

function Op {
    Param (
        # this operator is the reverse of -contains
        [switch] $isIn,

        # this operator is just an example 
        [switch] $Plus
    )

    if ($isIn) {
        if ($args.Length -ne 2) {
            throw "Requires two arguments"
        }

        return ($args[1] -contains $args[0])
    }
    elseif ($Plus) {
        if ($args.Length -ne 2) {
            throw "Requires two arguments"
        }

        return ($args[0] + $args[1])
    }
}

Example usage:

PS> $ExampleList = @("alpha", "bravo", "charlie")

PS> Op "alpha" -isIn $ExampleList
True

PS> Op "delta" -isIn $ExampleList
False

PS> Write-Host ("Answer: " + (Op 5 -plus 7))
Answer: 12
like image 37
Sam Porch Avatar answered Sep 22 '22 17:09

Sam Porch