Function 在函数中间更改参数的值

Function 在函数中间更改参数的值,function,powershell,switch-statement,string-formatting,Function,Powershell,Switch Statement,String Formatting,尝试创建一个PowerShell函数,该函数将使用多组前后颜色输出一行文本。我有一个定义颜色集的开关 该函数有一个参数定义开关值,另一个参数定义下一个颜色集(如果我可以使用该开关): function Write-Custom { param($Say,$ThenSay,$Level,$ExtraLevel) switch([array]$level) { none {$c = 'Black','White'

尝试创建一个PowerShell函数,该函数将使用多组前后颜色输出一行文本。我有一个定义颜色集的开关

该函数有一个参数定义开关值,另一个参数定义下一个颜色集(如果我可以使用该开关):

    function Write-Custom
    {
        param($Say,$ThenSay,$Level,$ExtraLevel)
        switch([array]$level)
        {
            none {$c = 'Black','White'}
            name {$c = 'Cyan','DarkBlue'}
            good {$c = 'White','DarkGreen'}
            note {$c = 'Gray','White'}
            info {$c = 'White','DarkGray'}  
            warn {$c = 'Yellow','Black'}
            fail {$c = 'Black','Red'}
        }
        $s = " $Say"
        $ts = " $ThenSay "
        Write-Host $s -ForegroundColor $c[0] -BackgroundColor $c[1]  -NoNewLine
        Clear-Variable Level
        $Level = $ExtraLevel
        Write-Host $ts -ForegroundColor $c[0] -BackgroundColor $c[1]    
    }

    Write-Custom -Say 'hi there' -Level 'name' -ThenSay 'stranger ' -ExtraLevel 'warn' 
似乎无法清除并重新定义$level变量。似乎输出“hi there”的前景/背景应为青色/暗蓝色,“陌生人”部分为黄色/黑色……但整个字符串为青色/暗蓝色


我需要创建一个更复杂的开关吗?

您需要每次调用该开关以获得不同的颜色集。一种方法是将函数放入函数中,例如:

function Write-Custom
{
    param($Say,$ThenSay,$Level,$ExtraLevel)

    function GetColors([string]$level)
    {
        switch([array]$level)
        {
            none {'Black','White'}
            name {'Cyan','DarkBlue'}
            good {'White','DarkGreen'}
            note {'Gray','White'}
            info {'White','DarkGray'}  
            warn {'Yellow','Black'}
            fail {'Black','Red'}
            default { throw "Unrecognized level $level" }
        }
    }

    $c = GetColors($Level)
    Write-Host " $Say" -ForegroundColor $c[0] -BackgroundColor $c[1]

    $c = GetColors($ExtraLevel)
    Write-Host " $ThenSay " -ForegroundColor $c[0] -BackgroundColor $c[1]
}

美好的我从未想过在函数中创建函数。谢谢