在PowerShell中跨多个函数向数组添加结果的最佳方法?

时间:2013-12-11 15:39:52

标签: powershell powershell-v2.0

我想对某些基础架构执行一系列检查,如果检查失败,请将其添加到列表中。在工作流程结束时,编写结果列表。伪代码:

Function CheckSomething
{
    # Perform a check here. If check failed, add to the results list.
}

Function CheckSomethingElse
{
    # Perform another check. If check failed, add to the results list.
}

Function ShowResults
{
    $results;
}

CheckSomething;
CheckSomethingElse;
ShowResults;

我想避免使用全局变量。你会如何解决它?使用collections.arraylist

更新

我尝试了@mjolinor的以下建议

Function CheckSomething
{
   # Perform a check here. If check failed, add to the results list
   $check = $true
   if ($check -eq $true) {$results[CheckSomething] = 'Pass'}
   else {$results[CheckSomething] = 'Fail}'
}

Function CheckSomethingElse
{
    # Perform another check. If check failed, add to the results list.
    $check = $false
    if ($check -eq $true) {$results[CheckSomethingElse] = 'Pass'}
    else {$results[CheckSomethingElse] = 'Fail}'

}

Function ShowResults
{
    $results;
}

$results = @{}
CheckSomething
CheckSomethingElse
ShowResults

我得到了:

Missing or invalid array index expression.
At C:\Users\moomin\Documents\errorsTest.ps1:5 char:36
+    if ($check -eq $true) {$results[ <<<< CheckSomething] = 'Pass'}
    + CategoryInfo          : ParserError: ([:String) [], ParseException
    + FullyQualifiedErrorId : MissingArrayIndexExpression

这是来自here的后续问题。

2 个答案:

答案 0 :(得分:1)

另一种选择是使用哈希表:

Function CheckSomething
{
   # Perform a check here. If check failed, add to the results list.
   if ($check -eq $true) {$results['CheckSomething'] = 'Pass'}
   else {$results['CheckSomething'] = 'Fail}'
}

Function CheckSomethingElse
{
    # Perform another check. If check failed, add to the results list.
    if ($check -eq $true) {$results['CheckSomethingElse'] = 'Pass'}
    else {$results['CheckSomethingElse'] = 'Fail}'
}

Function ShowResults
{
    $results;
}

$Results = @{}
CheckSomething
CheckSomethingElse
ShowResults

答案 1 :(得分:0)

引用您的初始帖子,我认为最简单的方法是采用原始方法并使用$Script:范围:

Function CheckSomething
{
    # perform a check here, if check failed add to the results list
    $Script:results += 'Added Content'
}

Function CheckSomethingElse
{
    # perform another check,  if check failed add to the results list
    $Script:results += 'Added Content'
}

Function ShowResults
{
    $results;
}

$results = @();
CheckSomething;
CheckSomethingElse;
ShowResults;

由于您已经在脚本级别定义$results,因此您只需要确保在函数内部通过追加$Script:在适当的范围内引用该变量。