PowerShell:如果未找到字符串,则会出现不必要的错误

标签 powershell if-statement foreach

我遇到了一个脚本问题,如果证书的到期时间在当前日期的 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 不会产生输出,因此没有 MatchesGroup 要询问的属性。将此行拆分为多个步骤可以在尝试访问对象的属性之前检查我们是否有要使用的对象。也就是说,我们尝试字符串匹配:

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

相关文章:

java - equals with strings 产生错误的结果

javascript - 制作一个复选框并检查是否已选中

java - 在增强型for循环中使用final for循环变量的目的是什么?

c# - 如何获取所有任务

windows - 当 PowerShell 脚本更新时,Doxygen 不读取 Doxyfile

powershell - 开始成绩单 : This host does not support transcription

sql - 使用 powershell 为单个事务中的多个文件调用 sqlcmd

arrays - Powershell:将 pracl 命令的输出通过管道传输到数组

excel - VBA For循环+ if语句错误

.net - 将项目添加到字典的 LINQ 方法