首页 > 解决方案 > 如何使用 Where-Object 过滤输出?

问题描述

我正在尝试获取有关 Windows 2019 上的应用程序证书的一些信息(名称和到期日期):

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

输出:

脚本输出 1

但是,如果我只想获得那些在不久的将来(例如 30 天)到期的证书怎么办?试图像这样过滤,但没有成功:

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'

(输出相同)

标签: powershell

解决方案


  1. [DateTime] minus [DateTime]为您提供[TimeSpan]表示周期的对象。转换为 numeric 时[Int],它使用ticks0.0001s。要使用某些时间单位(例如天)进行操作,您应该使用.TotalDays

  2. -le '30'由于类型转换,转换为字符串可能很危险。使用数字,而不是字符串:-le 30.

  3. [DateTime]::Today[DateTime]::Now不是你正在做的事情Get-Date可能更好;)


例子:

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

我建议不要计算差异,而是制作“$warningDate”变量:

$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)

推荐阅读