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.
% is an alias for the ForEach-Object cmdlet. An alias is just another name by which you can reference a cmdlet or function.
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.
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"}}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With