【问题标题】:How to send output of Powershell script to CSV如何将 Powershell 脚本的输出发送到 CSV
【发布时间】:2014-08-14 12:31:10
【问题描述】:

我获得了以下脚本来连接到 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-each 循环中的最后一行时,我得到一个无用的 CSV 文件,其中只有一列“#TYPE System.String”

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

【问题讨论】:

  • 可能需要查看 Format-Custom、Format-List、Format-Table 和 Format-Wide Cmdlet。我确定使用其中一种格式会在您想要导入 Excel 的布局中获得格式。

标签: powershell csv azure


【解决方案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...>}

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2018-11-29
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多