2013-02-15 98 views
1

嘗試創建一個PowerShell函數,該函數將使用多組前後顏色輸出單行文本。我有一個定義顏色集合的開關。更改函數中參數的值

函數有一個PARAM定義開關量和另一個PARAM,如果我能得到這個工作,定義了使用同一臺交換機的下一個顏色集:

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變量。似乎輸出'你好'應該有青/暗藍色的前景/背景,'陌生人'部分是黃色/黑色......但整個字符串出來青色/深藍色。

我是否需要創建一個更復雜的開關?

回答

3

您需要每次調用開關以獲取不同的顏色集。做到這一點的一種方法是在你的功能內部放置一個功能,例如:

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

不錯。從來沒有想過在函數內創建一個函數。謝謝! – 2013-02-16 04:53:56