Powershell export data to CSV with columns

Solution 1:

Instead of manually formatting each row in the CSV, you'll want to create a series of objects with properties corresponding to the column names you want, and then let Export-Csv take care of constructing the CSV file for you:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 
    
$Currentime = Get-Date -format "yyyyMMdd_hhmmtt" 
$filename = "FarmUsers" 
$datafile = ("{0}{1}.csv" -f $filename, $Currentime) 
    
$iissitedata = Get-SPWebApplication  
foreach ($farmsite in $iissitedata)
{ 
    foreach ($SiteCollection in $farmsite.sites)
    { 
        foreach ($web in $SiteCollection.Allwebs)
        {  
            foreach ($usersite in $web.users)
            {
                $data = [pscustomobject]@{
                    type     = "RootUser"
                    user     = $usersite
                    group    = '-'
                    weburl   = $web.url
                    webtitle = $web.name
                }
                $data | Export-Csv -LiteralPath $datafile -NoTypeInformation -Append
            } 
     
            foreach ($group in $web.Groups)
            { 
                foreach ($user in $group.users)
                {                           
                    $data = [pscustomobject]@{
                        type     = "GroupUser"
                        user     = $user
                        group    = $group
                        weburl   = $web.url
                        webtitle = $web.name
                    }
                    $data | Export-Csv -LiteralPath $datafile -NoTypeInformation -Append
                } 
            }    
            $web.Dispose() 
        } 
    } 
}