PowerShell: Output HashTable to CSV

function outputHashtableToCsv{
    param(
        $hashTable,
        $csvFile='C:\updateResults.csv',
        $headers=@('computerName','minutesToUpdate')
        )
    try{
        write-host $($hashTable|out-string)
        if(test-path $csvFile){        
            rename-item $csvFile "$csvFile.bak"
            write-warning "$csvFile currently exists. Hence, that previous file has been renamed to $csvFile.bak"
        }
        $hashTable.GetEnumerator() | `
            Select-Object -Property @{N=$headers[0];E={$_.Key}}, @{N=$headers[1];E={$_.Value}} | `
            Export-Csv -NoTypeInformation -Path $csvFile
        write-host "CSV has been created successfully: $csvFile"
        return $true
    }catch{
        write-warning $_
        return $false
    }    
}

Leave a Reply

Your email address will not be published. Required fields are marked *