我遇到了一个脚本问题,如果证书的到期时间在当前日期的 30 天内,该脚本应该打印出输出。但是我发现,如果现在找到过期纪元字符串,那么我会收到一条错误消息“无法索引到数组”,这会弄乱我的输出。
请告诉我如何仅在包含过期纪元字符串的文件上运行此脚本
$c = Get-Date (Get-Date).ToUniversalTime() -UFormat %s
$epochroundedtimes = [math]::Round($c)
$epochtimes = $epochroundedtimes + 2592000
Get-ChildItem -Path "C:\scripts\PALO" -File -Recurse |
ForEach-Object { $epochtimes } {
$certexp =
[double] ($_ | Select-String -pattern "expiry-epoch (\d+)$").Matches.Groups[1].Value
if ($certexp -le $epochtimes) {
$_.FullName
}
}
最佳答案
试试这个:
$c = Get-Date (Get-Date).ToUniversalTime() -UFormat %s
$epochroundedtimes=[math]::Round($c)
$epochtimes=$epochroundedtimes + 2592000
Get-ChildItem -Path "C:\scripts\PALO" -File -Recurse |
ForEach-Object {
$epochMatch = $_ | Select-String -pattern "expiry-epoch (\d+)$"
if($epochMatch)
{
$certexp = ([double]($epochMatch.Matches.Groups[1].Value))
if($certexp -le $epochtimes)
{
$_.FullName
}
}
}
编辑:根据评论添加简短说明
错误是由原始代码示例中的这一行生成的:
$certexp =
[double] ($_ | Select-String -pattern "expiry-epoch (\d+)$").Matches.Groups[1].Value
这是有问题的,因为如果目标文件不包含预期的字符串,Select-String
不会产生输出,因此没有 Matches
或 Group
要询问的属性。将此行拆分为多个步骤可以在尝试访问对象的属性之前检查我们是否有要使用的对象。也就是说,我们尝试字符串匹配:
$epochMatch = $_ | Select-String -pattern "expiry-epoch (\d+)$"
然后检查$epochMatch
是一个实际的对象:
if($epochMatch)
如果是这样,我们将检索匹配的值:
$certexp = ([double]($epochMatch.Matches.Groups[1].Value))
关于PowerShell:如果未找到字符串,则会出现不必要的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49804285/