Best way to add results to an array across multipl

2019-08-09 11:21发布

问题:

I want to perform a series of checks on some infrastructure, and if the check fails, add it to a list. At the end of the workflow, write the results list. Pseudo code:

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;

I would like to avoid using global variables. How would you solve it? Use a collections.arraylist?

Update

I tried the following suggestion from @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

And I get:

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

This is a follow-on question from here.

回答1:

Another option is to use a hash table:

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


回答2:

Referencing your initial post, I believe the simplest way would be to take your original approach and use the $Script: scope:

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;

Since you are defining $results at the script level already, you just need to make sure that inside your functions you are referencing that variable at the appropriate scope by append $Script:.