如何在Powershell中作为脚本变量将项添加到函数中的数组?

时间:2019-05-02 14:36:17

标签: powershell

我试图将项添加到我在函数外部声明的数组变量中。

这是我的代码的想法,非常简单:

function Test($NAME, $SPEED){
$fName = "testName"
$fSpeed = 100

if($status = ($fName -eq $NAME) -and ($fSpeed -eq $SPEED))
{}

else{
if($fName -ne $NAME)
{$errorMessages += "The name is not" + $NAME}

if($fSpeed -ne $SPEED)
{$errorMessages += "The speed is not" + $SPEED}
}
return $status
}

$script:errorMessages=@()
$result=@()

$result += Test -NAME "alice" -SPEED "100"
$result += Test -NAME "bob" -SPEED "90"
#result is an array of booleans that I need later on

$errorMessages

当我显示$ errorMessages时,这是我想要的预期输出:

The name is not alice
The name is not bob
The speed is not 90

但是,当我尝试在函数之外,甚至在“ else”块之外显示变量时,我什么也没打印出来。如何将错误消息正确添加到阵列?

1 个答案:

答案 0 :(得分:1)

您想通过脚本作用域调用errorMessages。因此,您必须在函数中使用$script:errorMessage(而不是$errorMessage)。

function Test($NAME, $SPEED) {
   $fName = "testName"
   $fSpeed = 100
   $status = ($fName -eq $NAME) -and ($fSpeed -eq $SPEED)
   if (!$status) { 

       if ($fName -ne $NAME) { 
           $script:errorMessages += "The name is not" + $NAME 
       }

       if ($fSpeed -ne $SPEED) { 
           $script:errorMessages += "The speed is not" + $SPEED 
       }
   }
   $status
}

$errorMessages = @()
$result = @()

$result += Test -NAME "alice" -SPEED "100"
$result += Test -NAME "bob" -SPEED "90"
#result is an array of booleans that I need later on

$errorMessages

现在您将获得预期的输出:

The name is notalice
The name is notbob
The speed is not90

还要注意PowerShell中的return语句-> stackoverflow answer

希望有帮助