Search code examples
powershellactive-directoryoutputdomaincontrollerpsobject

Two different outputs from psObject


I have following code which will write any users which are part of the group or not:

$Host.UI.RawUI.WindowTitle = "User Group Finder"
$groupname = Read-Host -Prompt 'Enter group name: '

Write-Host ""
Write-Host "People who are not in this group:" -ForegroundColor Red

$results = @()
$users = Get-ADUser  -Properties memberof -Filter * 
foreach ($user in $users) {
    $groups = $user.memberof -join ';'
    $results += New-Object psObject -Property @{'User'=$user.name;'Groups'= $groups}
    }

$results | Where-Object { $_.groups -notmatch $groupname } | Select-Object user

Write-Host "People who are in this group:" -ForegroundColor Green

$results | Where-Object { $_.groups -match $groupname } | Select-Object user

The code is working when i wanna have only one output from it.

But i want to have two different outputs (People who are in group and people who are not).

Problem is for now its combining outputs.

Is there any way i could generate two different output from one psObject?


Solution

  • Your group results are correctly separated.

    The problem is that you are using both the console through Write-Host and the pipeline (output of both results).

    Both are displayed on the console, but what goes through the pipeline is not synchronous with Write-Host

    That's why things appears out of order.

    Send the outpout to the host to fix by piping the results to Out-Host to preserve order when mixed with Write-Host statements.

    $results | Where-Object { $_.groups -notmatch $groupname } | Select-Object user | Out-Host
    Write-Host "People who are in this group:" -ForegroundColor Green
    $results | Where-Object { $_.groups -match $groupname } | Select-Object user | Out-Host
    

    | Out-String | Write-Host can also be used if you want to specify a different color for the output.