PowerShell,Get-WinEvent -FilterHashTable ID和数组的怪异行为

时间:2018-09-28 14:03:03

标签: arrays windows powershell get-winevent

我想做什么?

我使用Get-WinEvent运行-FilterHashTable函数,为ID参数提供了一组有趣的事件ID。

$IDS = 4720,4722,4723,4724,4725,4726,4727,4728,4729,4730,4731,4732,4733,4734,4735,4737,4738,4740,4741,4742,4743,4744,4745,4746,4747,4748,4749,4750,4751,4752,4753,4754,4755,4756,4757,4758,4759,4760,4761,4762,4763,4764,4767,4781

Get-WinEvent -ComputerName DC -FilterHashTable @{ LogName='Security'; ID=$IDS; }

此返回的错误:

# Get-WinEvent : No events were found that match the specified selection criteria.

(而且我知道匹配事件确实存在)

我注意到,在数组较小的情况下,该函数返回的结果是肯定的,因此,我尝试了几次:

  • 具有数组计数-le 23的直接调用可以正常工作;
  • 直接调用数组计数为-gt 23会导致错误。

看似适当的解决方案...

我假定{23}是Get-WinEvent的基础机制可以处理的参数的未记录限制,然后决定将调用分成多个具有较小数组的调用:

$MaxCount = 23
For ( $i = 0; $i -lt $IDS.count; $i += $MaxCount ) { 
    $IDSChunks += ,@( $IDS[ $i..($i+$MaxCount-1) ] ) 
}

通过这种方式,我们将数组分为两个,每个都包含-le 23个元素:

$IDSChunks | %{ $_ -join "," }
4720,4722,4723,4724,4725,4726,4727,4728,4729,4730,4731,4732,4733,4734,4735,4737,4738,4740,4741,4742,4743,4744,4745
4746,4747,4748,4749,4750,4751,4752,4753,4754,4755,4756,4757,4758,4759,4760,4761,4762,4763,4764,4767,4781

手动检查,并且按预期工作:

Get-WinEvent -ComputerName DC -FilterHashTable @{ LogName='Security'; ID=$IDSChunks[0]; }
Get-WinEvent -ComputerName DC -FilterHashTable @{ LogName='Security'; ID=$IDSChunks[1]; }

但是...

但是,这不是:

$IDSChunks | %{ Get-WinEvent -ComputerName DC -FilterHashTable @{ LogName='Security'; ID=$_; } }

并产生已经熟悉的错误:

# Get-WinEvent : No events were found that match the specified selection criteria.
# Get-WinEvent : No events were found that match the specified selection criteria.

为什么?

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

我仍在尝试调查原因,但是如果您将管道变量强制为数组,则可以使它正常工作。它已经是一个Object数组,但也许正在展开。这与您显式调用元素时应该没有什么不同。我同意这很奇怪

$IDSChunks | %{ Get-WinEvent -ComputerName dckan08ba -FilterHashTable @{ LogName='Security'; ID=@($_)} }

添加了详细的开关支持,该支持将转换为以空格分隔的字符串。它应该看起来像这样:

VERBOSE: Constructed structured query:
*[((System/EventID=4746) or (System/EventID=4747) or
(System/EventID=4748) or (System/EventID=4749) or (System/EventID=4750) or (System/EventID=4751) or
(System/EventID=4752) or (System/EventID=4753) or (System/EventID=4754) or (System/EventID=4755) or
(System/EventID=4756) or (System/EventID=4757) or (System/EventID=4758) or (System/EventID=4759) or
(System/EventID=4760) or (System/EventID=4761) or (System/EventID=4762) or (System/EventID=4763) or
(System/EventID=4764) or (System/EventID=4767) or (System/EventID=4781))].

但是,相反:

VERBOSE: Constructed structured query:
*[(System/EventID=4746 4747 4748 4749 4750 4751 4752
4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4767 4781)].