powershell - 如何使用 Where-Object 过滤输出?
问题描述
我正在尝试获取有关 Windows 2019 上的应用程序证书的一些信息(名称和到期日期):
Get-AdfsRelyingPartyTrust | ?{$_.EncryptionCertificate} `
| Select-Object name,
@{n="CertificateExpiration";e={($_ | Select-Object EncryptionCertificate -ExpandProperty EncryptionCertificate).notafter}} | Sort-Object CertificateExpiration
输出:
但是,如果我只想获得那些在不久的将来(例如 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'
(输出相同)
解决方案
[DateTime] minus [DateTime]
为您提供[TimeSpan]
表示周期的对象。转换为 numeric 时[Int]
,它使用ticks
0.0001s。要使用某些时间单位(例如天)进行操作,您应该使用.TotalDays
-le '30'
由于类型转换,转换为字符串可能很危险。使用数字,而不是字符串:-le 30
.[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)
推荐阅读
- npm - 尝试 npm install package 时出现安装错误
- scala - Gradle 不执行 scalatest
- reactjs - 如何解决数据表反应js中的表中没有可用数据的问题
- ansible - Ansible 检查主机文件
- javascript - firebase admin sdk nodejs 放置键/值数据
- reactjs - 在生产环境中处理 React 项目中的 cookie
- amazon-web-services - 如何使用带有 G-suite 的 AWS SSO 进行自动用户配置?
- reactjs - CSSStyleDeclaration 在 react 中使用 useRef 时没有给出任何值
- ios - 在 iOS 15 的呼叫目录扩展中经常出现此问题: Domain=com.apple.CallKit.error.calldirectorymanager Code=2 "(null)"
- reactjs - 如何在 NextJS 中更新标签的 src 而无需重新渲染整个组件