Steve
Steve

Reputation: 347

Powershell - Event Forwarding from Powershell Remoting Session - Inconsistent Behaviour

I am noticing a slightly inconsistent behaviour between PowerShell ISE and PowerShell Console. I am trying to run the below script, which attempts to display the forwarded event data from a remote PowerShell session on the host computer. It works as expected when run from ISE but when I run it from the PowerShell Console, no forwarded messages are displayed. But when I press the 'Tab' key then suddenly all the queued messages appear at once.

I have noticed this behaviour on Windows Server 2008 R2 as well as later OSes. I am using PowerShell 5.1.

Any ideas? Thanks.

Register-EngineEvent -SourceIdentifier RemoteEventOccured -MessageData 'RemoteEventOccured' -Action {
    Write-Host $event.MessageData
} | Out-Null

$RemoteJob = Invoke-Command -ComputerName localhost -AsJob -JobName MyRemoteJob -ScriptBlock {

    Register-EngineEvent -SourceIdentifier RemoteEventOccured  -Forward | Out-Null

    while($true){
        New-Event -SourceIdentifier 'RemoteEventOccured' -MessageData "$(Get-Date): Remote data received..." | Out-Null
        Start-Sleep -Seconds 5
    }
}

Upvotes: 1

Views: 107

Answers (1)

postanote
postanote

Reputation: 16096

The ISE will make things available (via autoloading) that you must explicitly initialize/call when running in the ISE. I.E., Forms namespaces, Security settings (TLS), etc. So, if you are saying that you won't see the output of the $RemoteJob info, you have to tell the consolehost about that.

So, using the Output cmdlets, or variable squeezing (which assigns the results to a variable while simultaneously sending the results to the screen.)

So, try these:

# Using Out-Host
$RemoteJob = Invoke-Command -ComputerName localhost -AsJob -JobName MyRemoteJob -ScriptBlock {

    Register-EngineEvent -SourceIdentifier RemoteEventOccured  -Forward | 
    Out-Null

    while($true)
    {
        New-Event -SourceIdentifier 'RemoteEventOccured' -MessageData "$(Get-Date): Remote data received..." | 
        Out-Null
        Start-Sleep -Seconds 5
    }
} | Out-Host



# Write
Write-Output $RemoteJob



# Variable squeezing
($RemoteJob = Invoke-Command -ComputerName localhost -AsJob -JobName MyRemoteJob -ScriptBlock {

    Register-EngineEvent -SourceIdentifier RemoteEventOccured  -Forward | 
    Out-Null

    while($true)
    {
        New-Event -SourceIdentifier 'RemoteEventOccured' -MessageData "$(Get-Date): Remote data received..." | 
        Out-Null
        Start-Sleep -Seconds 5
    }
})

Upvotes: 1

Related Questions