user4317867
user4317867

Reputation: 2448

Multiple regular expression matching

I'm a little lost on the best approach for filtering data (shown below) using multiple criteria.

As an example, MyServer2 and Sat 18:00 would result in MyServer2 and 04-23-16 1800 that I can output into two text files.

"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!"

My current approach is shown below, the two Where-Object lines but that is getting cumbersome and its not easy to read.

I'm also not sure how I can update the static "$((get-date).AddDays(7).ToString('MM-dd-yy')) 17:58" into something dynamic which does the date/time calculation and the outputs the date/time string. I've been able to use [datetime]"04/23/2016 18:00" - (get-date) but I'm just not sure how I can get the data into that format.

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"}

Upvotes: 0

Views: 58

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200373

I would recommend upgrading your input CSV with additional fields, at least for the day and start time of the maintenance window, but perhaps also for the name of the server group. That would allow to greatly simplify filtering/processing.

If you need to dynamically calculate the date of next Saturday you can do it like this:

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

Since you're using the same filter on both occasions you can combine the loops and do output via Add-Content. Still, wrapping the conditions as @RyanBemrose suggested improves the overall readability of the filter. Also, using the formatting operator to put a string into an otherwise empty string is pointless, so remove that.

... | 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'
}

Upvotes: 1

Related Questions