处理日期时,Export-Csv会引发错误

时间:2016-03-08 13:22:35

标签: csv powershell

我正在尝试搜索Active Directory并获取用户名的报告以及证书何时到期。这是我从其他来源拼凑而成的代码。当我在PowerShell窗口中手动运行它时,它会显示我想要的NotAfter日期。

enter image description here

但是当我尝试写入CSV文件时,它告诉我NotAfter值是“System.Object []”。一个网站提到使用JSON格式,但这对眼睛不是很友好。任何帮助将不胜感激。

$cert = Get-ADUser -LDAPFilter $StrFilter -server $domain -searchbase $searchOU -Properties "Certificates"
Foreach ($i in $cert)
{
    $tempobj = $cert.Certificates | foreach { New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $_ }

    If ($Cert.Certificates.Handle -eq $null)
    {
        $Rep = "" | Select "Account", "NotAfter"
        $Rep."Account" = $cert.name
        $Rep."NotAfter" = "N/A"
        $Myobj += $Rep
        $Rep = $null
    }
    Else
    {
        $Rep = "" | Select "Account", "NotAfter"
        $Rep."Account" = $cert.name
        $Rep."notAfter" = $tempobj.NotAfter
    }

    $Myobj += $Rep
    $Rep = $null
}

#After the loop, export the array to CSV
$Myobj | sort | export-csv -Path C:\xtemp\scripts\pshell\UserCerts.csv -notype

1 个答案:

答案 0 :(得分:1)

您需要在代码中进行一些重大更新... 这应该是一个起点:

$cert = Get-ADUser -LDAPFilter $StrFilter -server $domain -searchbase $searchOU -Properties "Certificates"
$cert = $cert | ? {$_.Certificates}
$Myobj = @()

Foreach ($i in $cert)
    {
    $tempobj = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $i.Certificates

    $Rep = "" | Select Account, NotAfter

    If ($i.Certificates.Handle -eq $null)
        {
        $Rep.Account = $i.name
        $Rep.NotAfter = "N/A"
        }
    Else
        {
        $Rep.Account = $i.name
        $Rep.NotAfter = $tempobj.NotAfter.ToString()
        }

    $Myobj += $Rep
    }