PowerShell证书过期脚本

holgip5t  于 2023-03-23  发布在  Shell
关注(0)|答案(1)|浏览(117)

我正在写一个脚本来检测SSO ADFS过期证书。我在电子邮件中发送列表。我试图在电子邮件中按最过期到最少过期对列表进行排序。
我想把这张单子按天排序,而不是按字母顺序

Clear
$Body=""
$Body = "<b>SSO Certificate Expiration:</b><br/>"

$ExpirationThreshold = 30
$CurrentDate = Get-Date
$ComparisonDate = (Get-Date).AddDays($ExpirationThreshold)
$FixFormat = Get-Date $ComparisonDate

$Trusts = Get-AdfsClaimsProviderTrust |
Select name, @{Name='TokenSigningCertificates'; Expression={[string]::join(";", ($_.TokenSigningCertificates.NotAfter| 
Group-Object Name | 
Foreach-Object {$_.Group | Sort-Object * | Select-Object -Last 1}))}} |
Sort-Object -Property name

foreach ($Trust in $Trusts) {
    $Dates = [nullable[datetime]]$Trust.TokenSigningCertificates 
 if ($Dates -ne $null -and $Dates.ToString("yyyy/MM/dd") -ge $CurrentDate.ToString("yyyy/MM/dd") -and $Dates.ToString("yyyy/MM/dd") -lt $FixFormat.ToString("yyyy/MM/dd")) {

    $Body = $Body + (($Trust.Name + " cert expiring in: " + '<b style="background-color:yellow">' + ($Dates - $CurrentDate).ToString("dd") + '</b>' +" days<br/>"))
 }
 elseif ($Dates -ne $null -and $Dates.ToString("yyyy/MM/dd") -lt $CurrentDate.ToString("yyyy/MM/dd")) {

    $Body = $Body + (($Trust.Name + " already expired (" + '<b style="color:red">' + ($CurrentDate - $Dates).ToString("dd") + '</b>' + " days ago)<br/>"))
 }
 }
 
 $Body = $Body + "<br/><br/><i>This Script Was Run From: $env:COMPUTERNAME</i>"
 
Write-host "Sending Email"
Send-MailMessage -SmtpServer "*****" -Body $Body -Credential $PSCredSG -From "*****" -To "*****" -Subject "Expiring SSO Certs" -BodyAsHtml
31moq8wy

31moq8wy1#

使用FRegex:

$filename = "c:\temp\test.txt"
$pattern = '^.*\((?<days>\d+).*'

$certificates = Select-String -Path $filename -Pattern $pattern
$table = [System.Collections.ArrayList]::new()
foreach($certificate in $certificates.Matches)
{
   $newRow = New-Object -TypeName psobject
   $newRow | Add-Member -NotePropertyName Days -NotePropertyValue ([int]$certificate.Groups["days"].Value)
   $newRow | Add-Member -NotePropertyName Certificate -NotePropertyValue $certificate.Value
   $table.Add($newRow)  | Out-Null
}
$table = $table | Sort-Object -Property Days -Descending
$table

使用以下输入文件

ABC already expirer (304 days ago)
CDE already expirer (200 days ago)
FGH already expirer (180 days ago)
IJK already expirer (40 days ago)
LMN already expirer (80 days ago)

结果:

Days Certificate
---- -----------
 304 ABC already expirer (304 days ago)
 200 CDE already expirer (200 days ago)
 180 FGH already expirer (180 days ago)
  80 LMN already expirer (80 days ago)
  40 IJK already expirer (40 days ago)

相关问题