You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写可接收所有输入类型的PowerShell极简函数?

问题:让PowerShell函数同时兼容命名参数与各类通用输入的简洁实现方法

有没有简单简短的方式,让PowerShell函数/cmdlet既能接收并处理管道、位置、未声明等所有类型的参数,同时还支持命名参数?要求命名参数单独处理,其余所有参数作为通用输入项处理。

以下是为实现该功能的函数编写的测试套件,其中开关参数-lower表示结果需转为全小写:

$tests = @(
    @{
        run = { test "a" }
        expected = 'A'
    },

    @{
        run = { test "a" -lower }
        expected = 'a'
    },

    @{
        run = { test "a" "b" }
        expected = 'AB'
    },

    @{
        run = { test "a" "b" "c" }
        expected = 'ABC'
    },

    @{
        run = { test  -lower @("a","b","c") }
        expected = 'abc'
    },

    @{
        run = { test "a" @("b","c") }
        expected = 'ABC'
    },

    @{
        run = { test @("a","b") "c" }
        expected = 'ABC'
    },

    @{
        run = { test "a" @("b") "c" }
        expected = 'ABC'
    },

    @{
        run = { test "a" @("b") @("c") }
        expected = 'ABC'
    },


    @{
        run = { "a" | test }
        expected = 'A'
    },

    @{
        run = { @("a") | test }
        expected = 'A'
    },

    @{
        run = { @("a", "b") | test -lower }
        expected = 'ab'
    },

    @{
        run = { @("a", "b", "c") | test }
        expected = 'ABC'
    },

    @{
        run = { @(@("a", "b", "c")) | test }
        expected = 'ABC'
    },

    @{
        run = { @("a", @("b", "c")) | test }
        expected = 'ABC'
    },

    @{
        run = { @(@("a", "b"), "c") | test }
        expected = 'ABC'
    },

    @{
        run = { @("a", @("b"), "c") | test }
        expected = 'ABC'
    },

    @{
        run = { @("a", @("b"), @("c")) | test }
        expected = 'ABC'
    },


    @{
        run = { "b" | test "a" }
        expected = 'AB'
    },

    @{
        run = { @("b") | test "a" }
        expected = 'AB'
    },

    @{
        run = { @("c", "d") | test @("a", "b") }
        expected = 'ABCD'
    },

    @{
        run = { @("d", "e", "f") | test "a" @("b", "c") }
        expected = 'ABCDEF'
    },

    @{
        run = { "c" | test -lower "a" "b" }
        expected = 'abc'
    },

    @{
        run = { @("e", @("f", "g")) | test @("a", "b") "c" "d" }
        expected = 'ABCDEFG'
    },

    @{
        run = { @(@("e", "f"), "g") | test "a" "b" @("c", "d") }
        expected = 'ABCDEFG'
    },

    @{
        run = { @("d", @("e"), "f") | test @("a", "b") "c" -lower }
        expected = 'abcdef'
    },

    @{
        run = { @("e", @("f"), @("g")) | test "a" @("b", "c") "d" }
        expected = 'ABCDEFG' }
)

运行测试的代码如下:

$tests | ForEach-Object {
    $actual  =  & $_.run
    if($actual -ne $_.expected){ Write-Host "expected: '$($_.expected)', actual: '$actual'" }
}

内容的提问来源于stack exchange,提问作者zzzggghhh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 19:16:21