2017-03-01 129 views
0

我面臨的問題是添加一個變量的循環計數,並將其傳遞給函數和打印細節。請提出你的明智建議。參數傳遞在PowerShell功能

我的代碼如下所示:

function CheckErrorMessage { 
    [CmdletBinding()] 
    Param (
     [Parameter(Mandatory = $true, Position = 0)] 
     [ValidateNotNullOrEmpty()] 
     $Plugin 

     , [Parameter(Mandatory = $true, Position = 1)] 
     [ValidateNotNullOrEmpty()] 
     $Report_Decission  
) 

switch ($Plugin){ 

    'plugin-1' { 

     $Report_Decission 

    } 

    'plugin-2' { 

     $Report_Decission 
    } 

    Default { 

    } 
} 
}#functions ends here 

$test_1 = "no report" 
$test_2 = "with report" 

for($i=1; $i -ne 3; $i++){ 

CheckErrorMessage 'plugin-1' "$test_$i" # i want to sent $test_1 or $test_2 from here 
CheckErrorMessage 'plugin-2' "$test_$i" 
} 

當我運行它,它打印

1 
1 
2 
2 

但我要像輸出:提前

no report 
no report 
with report 
with report 

感謝。

回答

1

你有實際調用該表達式,所以變量擴展,你必須逃離$用`,所以它不試圖擴大它

CheckErrorMessage 'plugin-1' $(iex "`$test_$i") 

調用-表達:

的invoke -Expression cmdlet計算或運行指定的字符串作爲命令並返回表達式或命令的結果。沒有Invoke-Expression,在命令行提交的字符串將會被返回(回顯)。

參考:https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/invoke-expression

編輯:另一種方式來做到這一點(可能是更好和更安全)由馬蒂亞斯

$ExecutionContext.InvokeCommand.ExpandString("`$test_$i") 
+0

我可能會去'ExpandString()',而不是:''$ ExecutionContext.InvokeCommand.ExpandString( 「'$ TEST_ $ I」)''如果說 –

+0

會高興IEX我的意思是一些細節它是如何工作的 –

+0

@EricIpsum更新了鏈接 – 4c74356b41

1

就是有點更容易理解的是使用Get-Variable的另一種方法。

... 
$test_1 = "no report" 
$test_2 = "with report" 

for($i=1; $i -ne 3; $i++) { 
    CheckErrorMessage 'plugin-1' (Get-Variable "test_$i").Value 
    CheckErrorMessage 'plugin-2' (Get-Variable "test_$i").Value 
}