【问题标题】:Change value of a param in the midst of a function在函数中间更改参数的值
【发布时间】:2013-02-15 22:46:43
【问题描述】:

尝试创建一个 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 变量。似乎输出“你好”的前景/背景应该是青色/深蓝色,“陌生人”部分是黄色/黑色……但整个字符串都是青色/深蓝色。

我需要创建一个更精细的开关吗?

【问题讨论】:

    标签: function powershell switch-statement string-formatting


    【解决方案1】:

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

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

    【讨论】:

    • 不错。我从来没有想过在函数内部创建函数。谢谢!
    猜你喜欢
    • 2015-11-27
    • 1970-01-01
    • 2023-03-14
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多