Home > Back-end >  pscustomobject multiple lines per row
pscustomobject multiple lines per row

Time:11-06

I have some code so far, but would like it to result in a table with multiple lines for users per group.

Currently, it creates a table like this:

Group Users
abcgroup1 Alice
abcgroup1 Bob
abcgroup2 Bob
abcgroup2 Jason
abcgroup3 Eve

I would like it to instead create a table like this:

Group Users
abcgroup1 Alice
Bob
abcgroup2 Bob
Jason
abcgroup3 Eve
$Groups = get-adgroup -Filter 'name -like "*abc*"'

$Results = foreach( $Group in $Groups ){

    Get-ADGroupMember -Identity $Group | foreach {

        [pscustomobject]@{

            Group = $Group.Name

            Users = $_.Name

            }

        }

    }

$Results

$Results | Export-Csv C:\abc_search.txt -NoTypeInformation

CodePudding user response:

You can use -join operator concatenating by CRLF `r`n. This will result in a multiline string:

$Groups = Get-ADGroup -Filter "name -like '*abc*'"
$Results = foreach($Group in $Groups)
{
    [pscustomobject]@{
        Group = $Group.Name
        Members = (Get-ADGroupMember -Identity $Group).Name -join "`r`n"
    }
}

$Results | Format-Table -Wrap -Autosize
$Results | Export-Csv C:\abc_search.csv -NoTypeInformation

Note that I'm using -Wrap on Format-Table, needed to correctly display multiline strings on the console.

The other option you could use is Out-String thought that would also require the use of .TrimEnd() method to get rid of the trailing new line:

Members = ((Get-ADGroupMember -Identity $Group).Name | Out-String).TrimEnd()
  • Related