Powershell中的动态单函数多名化和函数名参数化

eyh26e7m  于 2023-08-05  发布在  Shell
关注(0)|答案(1)|浏览(122)

我可以通过定义多个别名来调用函数吗
我的标准功能:

function Green { process { Write-Host -NoNewline $_ -ForegroundColor  Green } }
function Red { process { Write-Host -NoNewline $_  -ForegroundColor  Red } }
function Yellow { process { Write-Host -NoNewline $_  -ForegroundColor  Yellow } }

字符串
标准结果:

$var = "Hello, World"
Write-Output "$var" | Green        # WARNING: Dont like "<functionname> <param>"
Write-Output "$var" | Yellow       # WARNING: Dont like "<functionname> <param>"
Write-Output "$var" | Yellow       # WARNING: Dont like "<functionname> <param>"


预期功能:

function **Green,Red,Yellow** { process { Write-Host -NoNewline $_ -ForegroundColor **<functionName>** } }

5n0oy7gb

5n0oy7gb1#

这不是最好的解决方案,但这将实现您正在寻找的,基本上在ConsoleColor enum中为每个值动态定义一个函数。

$def = {
    param(
        [Parameter(ValueFromPipeline)]
        [object] $InputObject
    )
    begin {
        $pipe = { Write-Host -ForegroundColor $MyInvocation.MyCommand.Name }.
            GetSteppablePipeline()

        $pipe.Begin($true)
    }
    process {
        $pipe.Process($InputObject)
    }
    end {
        $pipe.End()
    }
}

# If you just want Green, Yellow and Red you can change to:
# 'Green', 'Yellow', 'Red' | ForEach-Object {
[System.Enum]::GetValues([System.ConsoleColor]) | ForEach-Object {
    & (New-Item "function:$_" -Value $def -Force) "Defined function: '$_'"
}

# Testing:
'foo' | Green
'bar' | Yellow
'baz' | Red

Magenta foo, bar, baz

字符串

相关问题