tring to list al;l, groups starting with SAS* and all users in them

i have gotten this far

 

Get-ADGroup -Filter {name -like 'SAS_*'} |
ForEach-Object {
echo "groupname:" $_
get-adgroupmember $_|select SamAccountName}|select SamAccountName

 

gives 

sas_vp
iii073
iii098
iii653

 

what i want is 

sas_vp,iii073 
sas_vp,iii098 
sas_vp,iii653 

 

any ideas on how i would do that ?

  • Try this and see if it fits you needs...
    I don't have groups called SAS, so, *Users* is my example...

    Clear-Host

    ForEach ($GroupName in (Get-ADGroup -Filter {name -like '*Users*'} ).Name)
    {
    ForEach ($AccountName in (Get-ADGroupMember $GroupName).SamAccountName)
    {
    $GroupName + ', ' + $AccountName
    }
    }

    # Abbreviated output
    <#
    Users, Domain Users
    Users, Authenticated Users
    Users, INTERACTIVE
    ...
    Domain Users, Administrator
    ...
    LabUsers, pm
    LabUsers, eng
    ...
    #>
  • In reply to postanote:

    hey that worked great! I cant seem to pipe that to export though how do i now write that to a file?

    what I did now is just redirect using > and >> not sure if that is the best way

    echo "NSID,GROUP" > C:\scripts\ps1\groups.csv

    ForEach ($GroupName in (Get-ADGroup -Filter {name -like 'SAS_*'} ).Name)
    {
    ForEach ($AccountName in (Get-ADGroupMember $GroupName).SamAccountName)
    {
    $AccountName + ', ' + $GroupName >> C:\scripts\ps1\groups.csv
    }
    }
  • In reply to rwm:

    also Just FYI here is the final script it gets the sas_* groups and writes it to a database table using a sql account and a commandline password

    param(
    [string]$pwd
    )
    Write-Host $pwd
    $conn = New-Object System.Data.SqlClient.SqlConnection
    $conn.ConnectionString = "Data Source=UDWSQLDEV02;Initial Catalog=UDW_DATA_DICTIONARY;Integrated Security = True; User ID = user01; Password = $pwd;" #Integrated Security=SSPI;"
    $conn.open()
    $cmd = New-Object System.Data.SqlClient.SqlCommand
    $cmd.connection = $conn
    $cmd.commandtext = "DELETE FROM AD_GROUPS_USERS"
    $cmd.executenonquery()

    echo "NSID,GROUP" > C:\scripts\ps1\groups.csv

    ForEach ($GroupName in (Get-ADGroup -Filter {name -like 'SAS_*'} ).Name)
    {
    ForEach ($AccountName in (Get-ADGroupMember $GroupName).SamAccountName)
    {
    $AccountName + ', ' + $GroupName #>> C:\scripts\ps1\groups.csv
    $cmd.commandtext = "INSERT INTO AD_GROUPS_USERS (SAMAccountName,groupName) VALUES('{0}','{1}')" -f $AccountName,$GroupName
    $cmd.executenonquery()
    }
    }
    $conn.close()
  • In reply to rwm:

    Your use of pipe to file is fine, sure there are other ways, but the PowerShell is all about flexibility.