Question:
I have the below script that I run, how can I get the output to be placed into a comma separated string?
1 2 |
Get-ADGroup -filter * -properties GroupCategory | ft objectguid, samaccountname |
Current Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
objectguid samaccountname ---------- -------------- f5b71a40-9405-4874-b9b0-b35e45346f63 WinRMRemoteWMIUsers__ 95a99aa1-a771-4f86-bdce-7a6a3f00057a Administrators 6a6ad877-180c-462b-9672-bfba20200cda Users 038b03cf-1171-4546-b0af-a7654823e289 Guests ed3995ae-6f77-492f-bcb5-bc197fa24996 Print Operators b1f8301a-78e1-47ab-9e51-8e55525acadf Backup Operators 3d23c4c0-71d9-4e08-a8ee-a9692a6ed61f Replicator d86e5619-5893-41b7-b3a8-eda4c2725562 Remote Desktop Users 473592e4-71c8-458f-b7fc-b474809933ff Network Configuration Operators c433a049-f9e5-404a-9940-5cf1f8ce4d82 Performance Monitor Users 1ce2daf3-5d97-4493-9ec1-c84a49326113 Performance Log Users 24b06a4c-f32b-4081-a002-6f1851f98256 Distributed COM Users |
Desired Output
1 2 |
f5b71a40-9405-4874-b9b0-b35e45346f63,WinRMRemoteWMIUsers__,95a99aa1-a771-4f86-bdce-7a6a3f00057a,Administrators,6a6ad877-180c-462b-9672-bfba20200cda,Users,038b03cf-1171-4546-b0af-a7654823e289,Guests,ed3995ae-6f77-492f-bcb5-bc197fa24996,Print Operators,b1f8301a-78e1-47ab-9e51-8e55525acadf,Backup Operators,3d23c4c0-71d9-4e08-a8ee-a9692a6ed61f,Replicator,d86e5619-5893-41b7-b3a8-eda4c2725562,Remote Desktop Users,473592e4-71c8-458f-b7fc-b474809933ff,Network Configuration Operators,c433a049-f9e5-404a-9940-5cf1f8ce4d82,Performance Monitor Users,1ce2daf3-5d97-4493-9ec1-c84a49326113,Performance Log Users,24b06a4c-f32b-4081-a002-6f1851f98256,Distributed COM Users |
I am passing this into a string and parsing the data remotely using JavaScript.
Answer:
That’s fairly easy and consists of two steps: First separating the GUID and account name with a comma:
1 2 3 4 5 |
$items = Get-ADGroup -filter * -properties GroupCategory | select objectguid,samaccountname $combined = $items | ForEach-Object { $_.objectguid + ',' + $_.samaccountname } |
and then joining all those strings with a comma into a single string:
1 2 |
$result = $combined -join ',' |
We could also do it differently: First decompose the objects into simply two strings:
1 2 |
$separated = $items | % { $_.objectguid; $_.samaccountname } |
and then joining all those with a comma:
1 2 |
$result = $separated -join ',' |
or take advantage of the
$OFS
variable which specifies with what separator arrays are converted to strings. Same start, we need a single array with everything that should be joined with a comma, and then we set the $OFS
variable and convert the array to a string:
1 2 3 |
$OFS = ',' $result = [string] $separated |