Skip to content

Instantly share code, notes, and snippets.

@rpunt
Created August 7, 2019 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpunt/e303c5d9ab25e28f7eaddaf7f4a6e248 to your computer and use it in GitHub Desktop.
Save rpunt/e303c5d9ab25e28f7eaddaf7f4a6e248 to your computer and use it in GitHub Desktop.
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
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!

@rpunt
Copy link
Author

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.

Thanks!

@AspenForester
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