2012-02-20 84 views
2

我想將兩個參數傳遞給我的函數,並根據結果設置變量(和變量名稱)。我一直在試圖做到這一點的方式如下:從函數返回值(從現有變量名稱設置變量)

$service_to_check_for = "ping" 

function check-service-monitored ($check_command,$check_name) { 
    if($service_to_check_for -eq $check_command) 
    { 
     $Value = "Yes" 
    } 
    else 
    { 
     $Value = "No" 
    }  

    $script:check_command = $check_command 
    $script:check_name = $check_name 
    $script:value = $Value 
} 

check-service-monitored "ping" "NagiosPing" 

echo "$check_name : $value" 

我想

 $NagiosPing = "Yes" 

但如何?

回答

4

只要確保你的函數打印出來的唯一的價值是結果:

$service_to_check_for = "ping" 

function check-service-monitored ($check_command,$check_name) { 
if($service_to_check_for -eq $check_command) 
{ 
    "Yes" 
} 
else 
{ 
    "No" 
}  

$script:check_command = $check_command 
$script:check_name = $check_name 
$script:value = $Value 
} 

$NagiosPing = check-service-monitored "ping" "NagiosPing" 
$NagiosPing 

的功能,現在提供的是Yes或No,只是把它分配給您的變量

+0

輸出的唯一謝謝你許多!!我沒有想到將函數設置爲一個變量! 這是我完成的代碼: \t $ service_to_check_for = 「平」 \t功能檢查服務監視($ check_command){ \t \t如果($ service_to_check_for -eq $ check_command) \t \t { \t \t \t $值= 「是」 \t \t} \t \t其他 \t \t { \t \t \t $值= 「否」 \t \t} \t \t \t \t返回$價值 \t} \t \t \t \t $ nagiosping =檢查服務監測的 「平」 \t回聲「顯示器:$ nagiosping 「 – Sune 2012-02-20 13:37:29

+0

@Sune然後接受我的解決方案 – 2012-02-20 13:41:17

+0

當然!出於某種原因,我無法(你可以暫時接受這個答案)。再次謝謝你!! – Sune 2012-02-20 13:44:14