powershell

Why does this code work outside of this function but not as a function?


If I run the code below outside of the function wrapper, it returns the expected values, but when I run them inside the function, $confirmed and $missing end up null:

Function Check-groups{

    param($uGroups,$kGroups)
    $confirmed = @()
    $missing = @()
    foreach($t in $uGroups){
        if($kGroups -contains $t){
            $confirmed += $t
        }else{}
    }
    
    Echo $confirmed
    foreach($t in $kGroups){
        if($confirmed -contains $t){}else{$missing += $t}
    }
    Echo "this is missing"
    Echo $missing
    Write-Host $user.name" does not have the following groups:"
    Write-Host $missing
}

Why is this? How can I make the function work.


Solution

  • If you want to access the values contained in $missing and $confirmed then you have to return them as output from your function:

    function Check-Groups {
    
        param(
          [string[]]$uGroups,
          [string[]]$kGroups
        )
        
        $confirmed = @()
        $missing = @()
        foreach($t in $uGroups){
            if($kGroups -contains $t){
                $confirmed += $t
            }
        }
    
        foreach($t in $kGroups){
            if($confirmed -notcontains $t){
                $missing += $t
            }
        }
    
        # these messages will be written straight to the screen buffer
        Write-Host "These groups are missing:"
        $missing |ForEach-Object { Write-Host " - '${_}'" }
        Write-Host "Total: $($missing.Count) group$(if($missing.Count -ne 1){'s'})"
    
        # the value after the return statement will be passed back to the caller as output
        return [pscustomobject]@{
            Confirmed = $confirmed
            Missing = $missing
        }
    }
    

    Now you just need to assign the output from the function to some local variable at the callsite:

    PS ~> $userGroups = 'Finance','AllUsers','FullTimeEmployees'
    PS ~> $kGroups = 'AllUsers','FullTimeEmployees','MailUsers'
    PS ~> $groupsAnalyzed = Check-Groups -uGroups $userGroups -kGroups $kGroups
    These groups are missing:
     - 'MailUsers'
    Total: 1 group
    PS ~> $groupsAnalyzed.Missing
    MailUsers
    PS ~> $groupsAnalyzed.Confirmed
    AllUsers
    FullTimeEmployees
    PS ~>