Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Return days until cert expiration
# exit codes reflect this script's use as a Sensu check
# replace "YOUR ISSUER HERE" with the CA of your choice
param (
[Parameter(Mandatory=$True)][int]$critical = $(throw "-critical - is required."),
[Parameter(Mandatory=$True)][int]$Warning = $(throw "-warning - is required."),
[Parameter(Mandatory=$False)][string]$computer = $env:COMPUTERNAME.Tolower()
)
$cert=$(get-childitem cert:LocalMachine\My -recurse | where-object { $_.Issuer -match "YOUR ISSUER HERE" } | select Subject,@{Name="DaysRemaining";Expression={($_.NotAfter).subtract([DateTime]::Now).days}})
$ExpiryDays=$cert.DaysRemaining
if ($ExpiryDays -gt $warning) {
Write-Host "'$computer' Cert is expiring in $ExpiryDays Days."
exit(0)
} elseif (($ExpiryDays -lt $warning) -and ($ExpiryDays -gt $critical)) {
Write-Host "'$computer' Cert is expiring in $ExpiryDays Days."
exit(1)
} elseif ($ExpiryDays -lt $critical) {
Write-Host "'$computer' Cert is expiring in $ExpiryDays Days."
exit(2)
} else {
Write-Host "Not able to get Cert Expiry status for 'CN=$computer'."
exit(3)
}
@AspenForester

This comment has been minimized.

Copy link

commented Aug 7, 2019

Mandatory Parameters shouldn't get default values. Will those actually throw, or does it just stop and ask for the value?
[dateTime]::now is functionally equivalent to Get-Date
I'm not a fan of Write-Host, but I'm guessing the caller only really cares about the exit codes.

Why not have the "Your issuer here" as a parameter, even if it's not mandatory and has a default value.

I like the use of exit!

@rpunt

This comment has been minimized.

Copy link
Owner Author

commented Aug 7, 2019

In the original case, I've got a known issuer that's consistent across all use-cases, so it was hard-coded.

The use of exit reflects that this is a sensu check; 0=green, 1=yellow, 2=red, 3=unknown.

Write-host sets the body of the check-result message as displayed in Uchiwa. There may be other output options that'll work.

I'll have to look further into the throw on mandatory params.

Thanks!

@AspenForester

This comment has been minimized.

Copy link

commented Aug 8, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.