使用powershell格式化CSV文件输出

时间:2019-05-19 17:23:42

标签: powershell csv

我编写了以下代码,将证书详细信息存储在一个csv文件中。它可以正常工作,但是在csv文件的每一行中都写入了开头的符号@{和结尾的}。在包含标题的第一列中,符号=也被写入书面。所以我不知道没有这些符号怎么填充我的csv文件

这是我编写的代码

$StartDate = Get-Date
 $CertPath = 'Cert:\LocalMachine\'

  $CertsDetail =  Get-ChildItem -Path $CertPath -Recurse | Where-Object {$_.PsIsContainer -ne $true } | ForEach-Object {                               
   $DaysLeft = (New-TimeSpan -Start $StartDate -End $_.NotAfter).Days
   If ($DaysLeft -lt 30) {
    $Under30 = $true
    $Text = "The Certificate is but valid about to expire"
}
Else {
    $Under30 = $false
}
If ($DaysLeft -lt 1) {
    $Expired = $true
    #$Not_Expired = $false
    $Text = "The Certificate is expired"
}
Else {
    $Expired = $false
    #$Not_Expired = $true
    $Text = "The Certificate is still valid and not going soon to expire"
}
[pscustomobject]@{Text=$Text;`
                Subject = $_.Subject;`
                ExpireDate = $_.NotAfter;`
                DaysRemaining = $DaysLeft;`
                Under30Days = $Under30;`
                Expired = $Expired;`
                #Not_Expired = $Not_Expired
                }

                }
         $obj = [PSCustomObject] @{
         'Example Header 1' = $null
         'Example Header 2' = $null
         'Example Header 3' = $null
         'Example Header 4' = $null 
         'Example Header 5' = $null 
         'Example Header 6' = $null 


$obj | Add-Content -Path 'C:\Users\hanna\Desktop\certificate.csv'
$CertsDetail | Add-Content -Path 'C:\Users\hanna\Desktop\certificate.csv'

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

$StartDate = Get-Date
$CertPath = 'Cert:\LocalMachine\'
$CertsDetail = Get-ChildItem -Path $CertPath -Recurse | 
    Where-Object { $_.PsIsContainer -ne $true } | ForEach-Object {                               
    $DaysLeft = (New-TimeSpan -Start $StartDate -End $_.NotAfter).Days
    if ($DaysLeft -lt 1) {
        $Under30 = $true
        $Expired = $true
        $Text = "The Certificate is expired"
    }
    elseif ($DaysLeft -lt 30) {
        $Under30 = $true
        $Expired = $false
        $Text = "The Certificate is but valid about to expire"
    }
    else {
        $Under30 = $false
        $Expired = $false
        $Text = "The Certificate is still valid and not going soon to expire"
    }
    [PSCustomObject]@{
        Text = $Text
        Subject = $_.Subject
        ExpireDate = $_.NotAfter
        DaysRemaining = $DaysLeft
        Under30Days = $Under30
        Expired = $Expired
    }
}
$CertsDetail | Export-Csv -Path 'C:\Users\hanna\Desktop\certificate.csv'