Private/Get-MyEvent.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
function Get-MyEvent {
    [CmdLetBinding()]
    param(
        [Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
        [Alias('IPAddress','__Server','CN')]
        [string[]]$ComputerName='localhost',
        [Parameter(ParameterSetName='FilterHashTable')]
        [ValidateNotNull()]
        [hashtable]$FilterHashTable,
        [Parameter(ParameterSetName='FilterXml')]
        [ValidateNotNull()]
        [xml]$FilterXml,
        [ValidateNotNull()]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
        [int64]$MaxEvents,
        [switch]$Oldest
    )

    begin {

        $ParameterSplat = @{}
        if ($Credential) {
            $ParameterSplat['Credential'] = $Credential
        }
        if ($MaxEvents) {
            $ParameterSplat['MaxEvents'] = $MaxEvents
        }
        if ($Oldest) {
            $ParameterSplat['Oldest'] = $true
        }

        $ComputerCounter = 0

    }

    process {

        foreach ($Computer in $ComputerName) {
            $Computer = $Computer.ToUpper()
            if ($ComputerCounter -gt 0) {
                Write-Progress -Id 1 -Activity "Searching for events..." -CurrentOperation $Computer -PercentComplete (($ComputerCounter / $ComputerName.count) * 100)
            }
            $ComputerCounter++
            Write-Verbose "$Computer : Searching for events..."

            try {
                if ($Computer -isnot [ipaddress]) {
                    [void][System.Net.Dns]::GetHostByName($Computer)
                }
                switch ($PsCmdlet.ParameterSetName) {
                    'FilterHashTable' {
                        Get-WinEvent -ComputerName $Computer -FilterHashtable $FilterHashtable -ErrorAction Stop @ParameterSplat
                    }
                    'FilterXml' {
                        Get-WinEvent -ComputerName $Computer -FilterXml $FilterXml -ErrorAction Stop @ParameterSplat
                    }
                }
            }

            catch {
                if ($_.CategoryInfo.Category -eq 'ObjectNotFound') {
                    Write-Verbose -Message "$Computer : No events were found that match the specified selection criteria"
                } else {
                    $PSCmdlet.ThrowTerminatingError($PSItem)
                }
            }

        }
    }

    end {

    }
}