简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM