Thursday, January 6, 2022

So you're trying to use Powershell Out-File or Add-Content to create a csv with data/a variable that has (contains) commas inside of it?

Below is the code example of why this is such a PITA. It uses Exchange Powershell to grab distribution groups from an OU and then to read the members of each group recursively.

When formatting for an Excel csv that has commas in the data, you have to put quotes around ONLY the cell data that innately contains a comma, if you put commas around each cell's data, only the first cell with commas contained in the data will format correctly and the next cell in that same row that has a comma inside of its data, will not format correctly, which will drive you bonkers if you are like me.

How it looks when wrong (row 2) vs correct (row 4)


The code below adds the data for each row into an array and then loops through it and only prepends/appends quotes to the cell data when the cell data itself has a comma within it. If you want to roll your own, it should be pretty easy to add your data for each cell to an array and then use the loop that has foreach ($outputTemp in $outputArr), down to the code $output = "";

I couldn't find this via a web search anywhere else on the internet, so hopefully this helps someone. Comment with questions.


$outFile = "c:\temp\filename.csv";
"ADGroupDN, ADGroupSam, MemberDN, MemberSam" | Out-File $outFile -Encoding utf8;
$groupCount = 0;
$memberCount = 0;
$adGroups = Get-ADGroup -SearchBase "OU HERE" -Filter * -ResultSetSize 99999999; # **************
#Write-Host "Adgroup count" $adGroups.Count;
foreach ($adGroup in $adGroups) 
{
    $groupCount++;
    $members = Get-ADGroupMember $adGroup -Recursive;
    foreach ($member in $members)
    {
        $memberCount++;
        $outputArr = New-Object System.Collections.ArrayList;
        $outputArr.Add($adGroup.DistinguishedName) | Out-Null;
        $outputArr.Add($adGroup.SamAccountName) | Out-Null;
        $outputArr.Add($member.distinguishedName) | Out-Null;
        $outputArr.Add($member.SamAccountName) | Out-Null;
    
        $index = 0;
        foreach ($outputTemp in $outputArr)
        {
            if ($outputTemp.ToString().Contains(","))
		    {
			    $output += "`"$outputTemp`",";
		    }
		    else
		    {
			    $output += $outputTemp + ",";
		    }

            $index++;
		
		    if ($index -eq $outputArr.Count)
            {
                if ($output.EndsWith(","))
                {
                    $output = $output.Remove($output.Length - 1);
                }
            }
        }

        $output | Out-File $outFile -Append -Encoding utf8;
        $outputTemp = $output;
        $output = "";
    }
}

Write-Host $groupCount;
Write-Host $memberCount;