如何将Powershell脚本的输出发送到CSV

时间:2014-08-14 02:44:11

标签: powershell csv azure

我获得了以下脚本来连接Azure订阅,获取所有证书并输出一些证书属性。 脚本工作正常,
我要做的是将输出发送到CSV文件,这样我就可以按证书到期日期(例如)进行排序,并将输出操作到电子表格报告中(例如)。

Powershell脚本

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"    }

我尝试了什么......

当我尝试用for this替换for-each循环中的最后一行时,我得到一个只有一列无用的CSV文件" #TYPE System.String"

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

1 个答案:

答案 0 :(得分:1)

您已经在循环中创建了自己的CSV行,因此您可以只写入磁盘:

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

在循环之前写下你的标题:

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

要使Export-CsvConvertTo-Csv正常工作,您需要使用这些字段作为属性来管道对象集合。您可以使用New-Object制作此类集合:

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