2012-02-20 53 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