如何创建自定义Powershell运算符? [英] How to create a custom Powershell operator?

查看:47
本文介绍了如何创建自定义Powershell运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Powershell中创建自定义运算符?而且,我该怎么做?我已经搜索过Google,但没有任何反应.

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 -包含元素"

$ExampleList -contains "element"

我已经创建了cmdlet(使用Powershell和C#),模块等,因此我只需要简单的笔触.

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

推荐答案

您可以创建前缀运算符,但不能创建前缀或后缀运算符,例如:

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
    }
}

使用方式如下:

$toolPath = ?: {[IntPtr]::Size -eq 4} {"$env:ProgramFiles(x86)\Tools"} {"$env:ProgramFiles\Tools"}}

这篇关于如何创建自定义Powershell运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆