简体   繁体   中英

Powershell AD Group Members Query

Bit of a noob to PS and I need to output a CSV file containing:

GroupName   Username      Email

I need to do this for 2 specific groups in AD and output to 1 CSV file. My problem is that I can do it individually, although I never get the actual group name in my output (Hence the 2 separate files), for the 2 groups, just not into 1 file.

This is what I am running:

import-module ActiveDirectory

## Variables

$Admin = Get-ADGroupMember -identity [grp_name] | Get-ADUser -properties Mail | Select sAMAccountName, Mail
$Contrib = Get-ADGroupMember -identity [grp_name] | Get-ADUser -properties Mail | Select sAMAccountName, Mail

## ======================================
## Output

$Contrib | Export-CSV C:\Temp\[grp_name].csv
$Admin | Export-CSV C:\Temp\[grp_name].csv

Any help would be massively appreciated.

I think in the way with the pipe you want to do you can't pass the name from the ad group in the beginning. For understanding I splittet / rewrote the code.

#Specifiy all ad groups you want in this arrays
[ARRAY]$arr_ADGroups = @("Group1","Group2","Group3")

#Set the output path for the csv
[STRING]$str_CSVPath = "C:\Temp\Testfile.csv"

#Import the modul
Import-Module -Name ActiveDirectory

#For each ad group
Foreach ($str_ADGroup in $arr_ADGroups) {

    #Foreach user in the ad group
    Foreach ($obj_ADUser in Get-ADGroupMember -Identity $str_ADGroup) {

        #Cretae an object with the propertys you need
        $obj_Propertys = "" | Select-Object -Property GroupName, Username, Email

        #Set the propertys
        $obj_Propertys.GroupName = $str_ADGroup
        $obj_Propertys.Username = $obj_ADUser.sAMAccountName
        $obj_Propertys.Email = $obj_ADUser.Mail

        #Export to csv --> -Append works only V3.0 or higher
        $obj_Propertys | Export-Csv -Path $str_CSVPath -Append
    }
}

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