简体   繁体   中英

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:

脚本输出 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)

  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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM