BJTYS
BJTYS

Reputation: 3

Get AD Group Names from List and Group Members Properties with Powershell

I'm trying to Get-Content from a text file which includes AD group names. Then from this group list get the AD user properties for each member samaccountname, name, enabled properties of the user. The output I'd like to see would look something like this for each group in the text file.

Group Name
samaccountname  name  enabled

I managed to get the correct output but cannot get it output properly as the Write-Host result cannot be output to a file. Here is the script that gets what I want (well sort of - the first group name appears above the header).

$ErrorActionPreference = "SilentlyContinue"  
Get-Content D:\ADGroups.txt | Where{$_ -ne $null -and $_.trim() -ne ""} |   
    foreach{  
        $Group = $_   
        Write-Host "$Group"  
        Get-ADGroup -Identity $Group -Properties members |  
            Select-Object -ExpandProperty members |  
            Get-ADUser -Properties samaccountname, enabled |  
            Select samaccountname, name, Enabled  
    }   

I've searched and found similar scripts but none of them produced the results I'm looking for.

Upvotes: 0

Views: 5503

Answers (1)

AP.
AP.

Reputation: 8921

You should simply be able to do (with optimizations):

# Apply Silent Errors to only the functions you trust
$SC = ${ErrorAction="SilentlyContinue"}
cat "D:\ADGroups.txt" @SC | ? {"$_".trim()} | % {
    $Group = $_ 
    "$Group"
    Get-ADGroup -Identity $Group -Properties members @SC |
        Select -ExpandProperty members |
        Get-ADUser -Properties samaccountname, enabled @SC |
        Select samaccountname,name,enabled
} | Out-File "D:\Final-Output.txt"

This is because Write-Host writes directly to the shell and is ignored by PowerShell's stdout stream handling.

Upvotes: 0

Related Questions