从函数返回值(从现有变量名设置变量)

时间:2012-02-20 13:28:29

标签: function powershell

我想将两个参数传递给我的函数,并根据结果设置一个变量(和变量名)。我一直试图通过以下方式做到这一点:

$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"

但是如何?

1 个答案:

答案 0 :(得分: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 

您的功能现在提供的唯一输出是“是”或“否”,只需将其分配给变量

即可