我认为必须有一种更优雅的方式来完成这项工作 可读性是一个优点,简单是美好的。 我认为我最终得到的东西有点可读。 无法帮助,但认为有更好的方法可以做到这一点。
建议?
从日志中读取记录以查找属于特定时间段的记录。
<#
from log get records which match any the following sets of conditions
Day of the week is
Monday through Thursday
AND time of day is
at or after 07:00 and before 08:00
OR
after 17:00 and at or before 22:00
OR
Day of the week is
Friday
AND time of day is
at or after 07:00 and before 08:00
OR
Day of the week is
Saturday
AND time of day is
at or after 11:00 and at or before 16:00
OR
Day of the week is
Sunday
AND time of day is
at or after 18:00 and at or before 23:00
#>
$201503_OC = $201503 |?{
( ( ( ( [int]($_.TimeStamp.DayOfWeek) -ge 1 ) `
-and ( [int]($_.TimeStamp.DayOfWeek) -le 4 ) ) `
-and ( ( ( ($_.TimeStamp.TimeOfDay) -ge "07:00" ) `
-and ( ($_.TimeStamp.TimeOfDay) -lt "08:00" ) ) `
-or ( ( ($_.TimeStamp.TimeOfDay) -gt "17:00" ) `
-and ( ($_.TimeStamp.TimeOfDay) -le "22:00" ) ) ) ) `
-or ( ( [int]($_.TimeStamp.DayOfWeek) -eq 5 ) `
-and ( ( ($_.TimeStamp.TimeOfDay) -ge "07:00" ) `
-and ( ($_.TimeStamp.TimeOfDay) -le "08:00" ) ) ) `
-or ( ( [int]($_.TimeStamp.DayOfWeek) -eq 6 ) `
-and ( ( ($_.TimeStamp.TimeOfDay) -ge "11:00" ) `
-and ( ($_.TimeStamp.TimeOfDay) -le "16:00" ) ) ) `
-or ( ( [int]($_.TimeStamp.DayOfWeek) -eq 0 ) `
-and ( ( ($_.TimeStamp.TimeOfDay) -ge "18:00" ) `
-and ( ($_.TimeStamp.TimeOfDay) -le "23:00" ) ) ) ) `
}
答案 0 :(得分:2)
您可以将复杂的条件放在函数或scriptproperty / script方法中。
看起来每个由OR
分隔的顶级条件树都会为您指出一些有意义的条件,是吗?它们没有这样命名,因此我将为它们组成名称以证明:
Day of the week is
Monday through Thursday
AND time of day is
at or after 07:00 and before 08:00
OR
after 17:00 and at or before 22:00
Day of the week is
Friday
AND time of day is
at or after 07:00 and before 08:00
Day of the week is
Saturday
AND time of day is
at or after 11:00 and at or before 16:00
Day of the week is
Sunday
AND time of day is
at or after 18:00 and at or before 23:00
$201503 | Add-Member -MemberType ScriptProperty -Name David -Value {
( ( ( [int]($this.TimeStamp.DayOfWeek) -ge 1 ) `
-and ( [int]($this.TimeStamp.DayOfWeek) -le 4 ) ) `
-and ( ( ( ($this.TimeStamp.TimeOfDay) -ge "07:00" ) `
-and ( ($this.TimeStamp.TimeOfDay) -lt "08:00" ) ) `
-or ( ( ($this.TimeStamp.TimeOfDay) -gt "17:00" ) `
-and ( ($this.TimeStamp.TimeOfDay) -le "22:00" ) ) )
}
未图示:实施Gerald,Daniel和Darian ScriptProperties的代码。
$201503_OC = $201503 | ? { $_.David -or $_.Gerald -or $_.Daniel -or $_.Darian }
当然这有用性取决于你如何使用它,但如果你给条件语更有意义的名字,比如&#34; HappyHour&#34;或者&#34; WeekendBrowsers&#34;或者其他什么,那么得到的逻辑代码就更具可读性,即使组成条件的代码仍然难以解析。
答案 1 :(得分:1)
使用-contains
简化范围检查,并将数字移至LH方以消除对.DayOfWeek
的投射[int]
。由于时间范围是小时边界,因此只需使用.Hour
属性即可简化时间比较。
$201503_OC = $201503 |
Where {
( 1..4 -contains $_.DayOfWeek -and 17..21 + 7 -contains $_.Hour ) -or
( 5 -eq $_.DayOfWeek -and 7 -eq $_.Hour ) -or
( 6 -eq $_.DayOfWeek -and 11..15 -contains $_.Hour ) -or
( 0 -eq $_.DayOfWeek -and 18..22 -contains $_.Hour )
}