Search code examples
powershellactive-directory

Get-Adgroupmember exported to single row


We have an application that reads a text file for license assignment and currently is manually managed.

the format consists of a single row for each AD Group, The row starts to the word "Group", followed by the AD Group name and then with the users SAMAccountName and all members in a single row... there is also some static information that does not change at the bottom of the file...

Group ADGroupName1 usersamaccountname1 usersamaccountname2 usersamaccountname3 Group ADGroupName2 usersamaccountname1 usersamaccountname2 usersamaccountname3 Group ADGroupName3 usersamaccountname1 usersamaccountname2 usersamaccountname3

Include this text as static Include this text also Include this text as well

##########################

found this base script on another post...

Get-ADGroup -Filter "Name -like 'humdrives'" |
ForEach-Object {
$Members = Get-ADGroupMember -Identity $_ -Recursive
[PSCustomObject]@{
StaticV1 = "Group"
Group = $_.Name
Members = $Members.sAMAccountName
}
}

StaticV1 Group Members


Group ADGroupName1 {Sam1, Sam2, Sam3, Sam4...}

and it is really close, except I am not able to get past the truncated output, nor have I been able to get the data exported correctly text file.


Solution

  • You can use the -join operator to produce the desired string:

    Get-ADGroup -Filter "Name -like 'humdrives'" |ForEach-Object {
        $Members = Get-ADGroupMember -Identity $_ -Recursive
        # drop all values into array subexpression, then -join 
        @(
            "Group"
            $_.Name
            $Members.sAMAccountName
        ) -join ' '
    } |Set-Content -Path export.txt
    

    You can then append additional content to the file with the Add-Content cmdlet:

    @'
    
    Include this text as static
    Include this text also
    Include this text as well
    
    ##########################
    '@ |Add-Content -Path export.txt