Vikings Dood
Vikings Dood

Reputation: 51

Apply conditional to output of a commandlet

I want to output the result of the commandlet (Invoke-Command) on success and add a custom message if the result is null. The code as shown below produces the desired results except in the event of a null response, it simply outputs nothing on that line.

I can not pipe directly to an if statement, nor can I output on 2 opposing conditions (True & False). Is it possible to get a custom response on $null while not suppressing the normal output on success?

Invoke-Command -ComputerName PC1, PC2, PC3 -Scriptblock {get-eventlog system | where-object {$_.eventid -eq 129} | select MachineName, EventID, TimeGenerated, Message -last 1}

If you run the example code block assuming that PC1 and PC3 have the event ID but PC2 does not, the output will simply skip PC2.

I want to output something like "Event Not found" in that case.

Placing the entire thing in a loop and then running the results through another conditional loops destroys performance so that is not an ideal solution.

Upvotes: 0

Views: 149

Answers (1)

Patrick
Patrick

Reputation: 2208

I would create a new object for returning from Invoke-Command. So you are sure you will receive from every host something even the event log is not present. And might you can change get-eventlog to Get-WinEvent. Get-WinEvent was for my tasks the most time faster than get-eventlog.

[System.Management.Automation.ScriptBlock]$Scriptblock = {
    [System.Collections.Hashtable]$Hashtable = @{
        WinEvent = Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 129 } -MaxEvents 1 -ErrorAction SilentlyContinue #-ErrorAction SilentlyContinue --> otherwise there is an error if no event is available
    }

    return (New-Object -TypeName PSCustomObject -Property $Hashtable)
}

Invoke-Command -ComputerName 'PC1', 'PC2', 'PC3' -Scriptblock $Scriptblock

Upvotes: 1

Related Questions