PS Get-WinEvent throw'手柄无效'

时间:2016-03-02 15:04:09

标签: powershell applocker get-winevent

我有一个主机名列表,我希望从中提取所有与AppLocker相关的事件日志,尤其是那些具有级别警告和/或错误的日志。 我精心制作了这个剧本:

$ComputersToCheck = Get-Content 'X:\ListWithTheNames.txt'
foreach($OneHost in $ComputersToCheck)
{
try
{
    $EventCollection = Get-WinEvent -LogName "Microsoft-Windows-AppLocker/EXE and DLL" -ComputerName $OneHost -Credential $CredentialFromUser
    foreach ($SingelEvent in $EventCollection)
    {
        if($SingelEvent.LevelDisplayName -ne "Information")
        {
            $pathtosaveto = 'SomeFileName.txt'
            $ResultString += $SingelEvent | Select Message,MachineName,UserId | Export-Csv -Path $pathtosaveto -Append                
            }
        }
    }
catch 
{
    //handling exceptions
 }    
}

这种方法有一段时间了,但经过一段时间后我得到了一个错误:

Get-WinEvent : The remote procedure call failed
At X:\FileName.ps1:22 char:28
+         $EventCollection = Get-WinEvent -LogName "Microsoft-Windows-AppLocker/EX ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Get-WinEvent], EventLogException
+ FullyQualifiedErrorId : The remote procedure call failed,Microsoft.PowerShell.Commands.GetWinEventCommand

脚本开始发出这样的错误之后:

Get-WinEvent : The handle is invalid
At X:\FileName.ps1:22 char:28
+         $EventCollection = Get-WinEvent -LogName "Microsoft-Windows-AppLocker/EX ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Get-WinEvent], EventLogException
+ FullyQualifiedErrorId : The handle is invalid,Microsoft.PowerShell.Commands.GetWinEventCommand

我的第一个想法是它与脚本尝试访问的主机有关,但列表中的下一个是与前一个相同的类型(Os,甚至是相同的模型)。

我运行了3次脚本,并且每次输出大小都不同(可能是因为没有相同的主机在线使用相同数量的日志)。 该脚本应该针对超过700个主机运行,需要一个特殊帐户,由Get-Credential提示,存储在变量中并将Get-WinEvent作为参数传递给它。

说实话,我坚持这个问题,不确定是什么导致这个和为什么。

如果有人有想法请与我分享:)

1 个答案:

答案 0 :(得分:0)

尝试尝试捕获对失败主机和空对象的引用。您可以编写收到的异常但我没有在其中包含这个以使failedhosts文件易于阅读。希望我能抓住它并且没有真正的案例进行测试。

$ComputersToCheck = Get-Content 'X:\ListWithTheNames.txt'
foreach($OneHost in $ComputersToCheck) {
try {
    $EventCollection = Get-WinEvent -LogName "Microsoft-Windows-AppLocker/EXE and DLL" -ComputerName $OneHost -Credential $CredentialFromUser -ErrorAction Stop

    if($EventCollection) { 
        foreach ($SingelEvent in $EventCollection) {
            if($SingelEvent.LevelDisplayName -ne "Information") {
                $pathtosaveto = 'SomeFileName.txt'
                $ResultString += $SingelEvent | Select Message,MachineName,UserId | Export-Csv -Path $pathtosaveto -Append                
                }
            }
        } else {
            Out-File -InputObject $($OneHost + " Empty Event Collection") -FilePath "C:\FailedHosts.txt" -Append -Encoding ascii 
        }
    } 
catch {
    Out-File -InputObject $($OneHost + " Failed Connection") -FilePath "C:\FailedHosts.txt" -Append -Encoding ascii 
 }    
}