多个正则表达式匹配

时间:2016-04-16 21:16:17

标签: regex powershell

我在使用多个标准过滤数据(如下所示)的最佳方法上有点迷失。

例如,MyServer2Sat 18:00会产生MyServer204-23-16 1800,我可以将其输出到两个文本文件中。

"Server","MaintenanceWindow","Ping","LastReboot"
"MyServer1","NoDeadline","Alive","4/8/2016 2:44:32 PM"
"MyServer2","NA - DYNALG - SRV - Patching - Prod - Sat 18:00","Alive","4/16/2016 10:00:47 AM"
"YourServer","NA - All DA Servers - Patching - Prod - Fri 22:00","Alive","Access Denied!"

我目前的方法如下所示,两条Where-Object行,但这样做很麻烦而且不容易阅读。

我也不确定如何将静态"$((get-date).AddDays(7).ToString('MM-dd-yy')) 17:58"更新为动态日期/时间计算和输出日期/时间字符串。我已经能够使用[datetime]"04/23/2016 18:00" - (get-date),但我不确定如何将数据转换为该格式。

Where-Object {$_ -like '*sat?18:00*' -and $_.MaintenanceWindow -notmatch 'all.da.servers' -and $_.Server -match "^My"} | % {"{0}" -f $_.Server}

Where-Object {$_ -like '*sat?18:00*' -and $_.MaintenanceWindow -notmatch 'all.da.servers' -and $_.Server -match "^My"} | % {"{0}" -f $_.MaintenanceWindow -replace "^NA.+", "$((get-date).AddDays(7).ToString('MM-dd-yy')) 17:58"}

1 个答案:

答案 0 :(得分:1)

我建议使用其他字段升级输入CSV,至少在维护窗口的日期和开始时间,但也可能是服务器组的名称。这样可以大大简化过滤/处理。

如果您需要动态计算下周六的日期,可以这样做:

$today = [DateTime]::Today
$nextSaturday = $today.AddDays((7 - $today.AddDays(1).DayOfWeek))

由于您在两种情况下都使用相同的过滤器,因此您可以组合循环并通过Add-Content进行输出。尽管如此,将条件包装为@RyanBemrose建议可以提高过滤器的整体可读性。此外,使用格式化运算符将字符串放入否则为空的字符串是没有意义的,所以删除它。

... | Where-Object {
  $_ -like '*sat?18:00*' -and
  $_.MaintenanceWindow -notmatch 'all.da.servers' -and
  $_.Server -match '^My'
} | ForEach-Object {
  $_.Server | Add-Content 'file1.txt'
  $_.MaintenanceWindow -replace '^NA.+', ('{0:MM-dd-yyy} 17:58' -f $nextSaturday) |
    Add-Content 'file2.txt'
}
相关问题