Home > Software design >  write array in one cell in PowerShell with values listed under each other
write array in one cell in PowerShell with values listed under each other

Time:08-12

I’m unable to figure out how to write the content of the array (please see first screenshot) each listed under each other. I’ve tried -join "," -join "`n" but without any luck.

$azSubs = Get-AzSubscription 

# Set array
$Results = @()

foreach($azSub in $azSubs){
    #Get-AzSubscription -SubscriptionName $azSub.Name | Set-AzContext
    az account set --subscription $sub.Name
    $diagSettings = Get-AzDiagnosticSetting -ResourceId "/subscriptions/$azSub" -Wa 0
    $law = az monitor log-analytics workspace show --resource-group $diagSettings.WorkspaceId.Split('/')[-5] --workspace-name $diagSettings.WorkspaceId.Split('/')[-1] | ConvertFrom-Json
        $item = [PSCustomObject]@{
                Subscription = $azSub.Name
                DiagnosticSettingName = $diagSettings.Name
                ActivityLogs = $diagSettings.Logs.Category -join ","
                IsEnabled = $diagSettings.Logs.Enabled -join ","
                LogAnalytics = $law.Name
                RetentionInDays = $law.retentionInDays
            }
        $Results  = $item

    }

$Results | Export-Csv -NoTypeInformation -Path ".\LogAnalyticsWorkspaces.csv"

data

How the data is written to csv

How I would like it to be written UPDATE: The solution provided works. I have one question. Is there a way to basically for the subscription column to write the subsription name once, instead for each line ? Results

I can merge the cells in Excel, but was wondering if this can be done within the script: Nice to have

Any help is much appreciated! Tahnk you !

CodePudding user response:

Export-Csv creates exactly 1 row per object you provide as input - so to have it create more rows, simply create more objects:

foreach($azSub in $azSubs){
    #Get-AzSubscription -SubscriptionName $azSub.Name | Set-AzContext
    az account set --subscription $sub.Name
    $diagSettings = Get-AzDiagnosticSetting -ResourceId "/subscriptions/$azSub" -Wa 0
    $law = az monitor log-analytics workspace show --resource-group $diagSettings.WorkspaceId.Split('/')[-5] --workspace-name $diagSettings.WorkspaceId.Split('/')[-1] | ConvertFrom-Json

    foreach($log in $diagSettings.Logs){
        $item = [PSCustomObject]@{
            Subscription = $azSub.Name
            DiagnosticSettingName = $diagSettings.Name
            ActivityLogs = $log.Category
            IsEnabled = $log.Enabled
            LogAnalytics = $law.Name
            RetentionInDays = $law.retentionInDays
        }
        $Results  = $item
    }
}
  • Related