rGA145
rGA145

Reputation: 204

How to filter output with Where-Object?

I'm trying to get some info about applications cert on Windows 2019 (name and expiration date):

Get-AdfsRelyingPartyTrust | ?{$_.EncryptionCertificate} `
| Select-Object name,
@{n="CertificateExpiration";e={($_ | Select-Object EncryptionCertificate -ExpandProperty EncryptionCertificate).notafter}} | Sort-Object CertificateExpiration

Output:

Script output 1

But what if I want to get only those certs, which expire in near future (30 days for example)? Tried to filter like this, but with no success:

Get-AdfsRelyingPartyTrust | ?{$_.EncryptionCertificate} `
| Select-Object name,
@{n="CertificateExpiration";e={($_ | Select-Object EncryptionCertificate -ExpandProperty EncryptionCertificate).notafter}} | Sort-Object CertificateExpiration `
| Where-Object ($_.CertificateExpiration - (Get-Date)).Days -le '30'

(output is same)

Upvotes: 0

Views: 1007

Answers (1)

filimonic
filimonic

Reputation: 4634

  1. [DateTime] minus [DateTime] gives you [TimeSpan] object which is representation of period. When converting to numerical [Int], it uses ticks which is 0.0001s. To operate with some time units like Days, you should use .TotalDays

  2. Converting to string -le '30' can be dangerous because of type conversion. Use numbers, not strings: -le 30.

  3. [DateTime]::Today and [DateTime]::Now instead of what you're doing with Get-Date maybe better ;)


Example:

Get-ChildItem 'Cert:\LocalMachine\My' | 
  Where-Object {$_.HasPrivateKey -eq $true} |
  Where-Object {($_.NotAfter - [DateTime]::Today).TotalDays -gt 30}

Instead of computing difference, I'd recommend to make "$warningDate" variable:

$warningDate = [DateTime]::Today.AddDays(30)
$warnedCerts = @(Get-ChildItem 'Cert:\LocalMachine\My' | 
   Where-Object {$_.NotAfter -le $warningDate})  # Use @() to force array if you're not sure on number of elements returned)

Upvotes: 2

Related Questions