0

I want to export the results of a WebApp to a CSV file, however Export-CSV is only exporting the last object. It seems like something is going wrong on the part of PSCustomObject but I can't figure out why. Any idea's?

$outputForCsv = ""
foreach ($rg in $resourceGroups) {
    $rgName = $rg.ResourceGroupName
    $webAppsInRg = Get-AzWebApp -ResourceGroupName $rgName
    $webAppNamesInRg = $webAppsInRg.Name

    foreach($webAppName in $webAppNamesInRg){
        $webApp = (Get-AzWebApp -ResourceGroupName $rgName -Name $webAppName)
        $tls = $webApp.SiteConfig.MinTlsVersion
        $http20Enabled = $webApp.SiteConfig.Http20Enabled
 
        $outputForCsv +=
            [PSCustomObject]@{
            ResourceGroup = $rg.ResourceGroupName
            WebAppName = $webAppName
            MinTlsVersion = $tls
            Http20Enabled = $http20Enabled
            }
    }
}

$outputForCsv | Export-Csv "data.csv" -delimiter ";" -NoTypeInformation
Jay
  • 189
  • 4
  • 12
  • 5
    Put this at the begining to ensure it is an array `$outputForCsv = @()` instead of `$outputForCsv = ""` – Itchydon May 06 '21 at 14:50
  • 8
    That, or just remove `""` completely and assign the output from the whole `foreach` to `$outputForCsv` – Mathias R. Jessen May 06 '21 at 14:52
  • 2
    I appreciate it, @Itchydon. – mklement0 May 06 '21 at 16:44
  • 1
    In short: In order to collect output produced in a loop in an array with `+=`, the target variable must be _initialized as an array_ (`$output = @()`); however, using a loop statement such as `foreach` as an _expression_ and letting PowerShell collect the results for you (`$output = foreach (...) ...`) is both simpler and much more efficient - see [this answer](https://stackoverflow.com/a/59278604/45375) to the linked duplicate. – mklement0 May 06 '21 at 16:50

0 Answers0