Skip to content

Instantly share code, notes, and snippets.

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}})
if ($ExpiryDays -gt $warning) {
Write-Host "'$computer' Cert is expiring in $ExpiryDays Days."
} elseif (($ExpiryDays -lt $warning) -and ($ExpiryDays -gt $critical)) {
Write-Host "'$computer' Cert is expiring in $ExpiryDays Days."
} elseif ($ExpiryDays -lt $critical) {
Write-Host "'$computer' Cert is expiring in $ExpiryDays Days."
} else {
Write-Host "Not able to get Cert Expiry status for 'CN=$computer'."
Copy link

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!

Copy link

rpunt 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.


Copy link

AspenForester commented Aug 8, 2019 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment