Azure – How to send output of Powershell script to CSV

azurecsvpowershell

I have been given the following script to connect to an Azure subscription, get all the certificates and output some of the certificate properties.
The script works fine,
What I am trying to do is send the output into a CSV file so I can sort by certificate expiry-date (for example) and manipulate the output into spreadsheet reports (for instance).

Powershell Script

Set-AzureSubscription 'MySubscription'
Select-AzureSubscription 'MySubscription'

$enc = [system.Text.Encoding]::UTF8
$azcerts = Get-AzureService | Get-AzureCertificate
foreach ($azcert in $azcerts) {      
    $bytes = $enc.GetBytes($azcert.data) 
    $cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate -ArgumentList @(,$bytes)    
    $subjectstring = $cert.Subject
    $expirydate = $cert.GetExpirationDateString()
    $servicename = $azcert.ServiceName
    $thumprint = $azcert.Thumbprint
    $cnstring = $subjectstring -replace "(CN=)(.*?),.*",'$2'    
    Write-Output "$servicename, $cnstring, $expirydate, $thumprint"    }

What I have tried…

When I try to replace the last line in the for-each loop with this I get a useless CSV file with only one column "#TYPE System.String"

"$servicename, $cnstring, $expirydate, $thumprint" | Export-Csv "outputfile.csv" -append -NoTypeInformation

Best Solution

You've made you're own CSV lines in the loop so you can just write to disk:

"$servicename, $cnstring, $expirydate, $thumprint" | Out-File -FilePath output.csv -Append -Encoding ASCII

before the loop write your headers:

"servicename, cnstring, expirydate, thumprint" | Out-File -FilePath output.csv -Encoding ASCII

For Export-Csv or ConvertTo-Csv to work you'd need to pipe a collection of objects with these fields as properties. You could make such a collection using New-Object:

New-Object -TypeName PsObject -Property @{servicename=$servicename;cnstring=$cnstring <ETC...>}