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

问题描述 投票:1回答:2

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

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的后续问题。

powershell powershell-v2.0
2个回答
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

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:在适当的范围内引用该变量。

© www.soinside.com 2019 - 2024. All rights reserved.