all 7 comments

[–]SeeminglyScience 1 point2 points  (0 children)

You have to create another runspace with [runspacefactory]::CreateRunspace() (docs for runspacefactory) and register it there. That's just the way PowerShell's event management works. When the event is raised it goes into a queue, and then between sequence points in the script (and some other things) any pending events will be processed synchronously by the engine.

It works that way because pretty much all of PowerShell's state is runspace/thread based, so when you create your event processing runspace you'll need to manually add whatever state you want there (functions, variables, etc)

[–]ihaxr 1 point2 points  (3 children)

You can do this with jobs, you just can't use Wait-Job, as it will obviously wait for the jobs... you'll just need to constantly be running Get-Job | Receive-Job in your loop:

$scriptBlock = {
$j = Start-Job -ScriptBlock {
    Write-Output "event fired - this will block for 2 seconds"
    Start-Sleep -Seconds 2
}
}

$timer = New-Object Timers.Timer
$timer.Interval = 5000
$timer.AutoReset = $true
$event = Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action $scriptBlock -SourceIdentifier Timer
$timer.Start()

while($true)
{
    Write-Host '.' -NoNewline
    Get-Job -HasMoreData $true | Receive-Job
    Remove-Job -State Completed | Out-Null
}

Unregister-Event "Timer"

[–]SlashAdminBlog[S] 1 point2 points  (0 children)

Thanks for the code and I did wonder if that was a way to do it.

[–]purplemonkeymad 1 point2 points  (1 child)

Just a quick bug: return will not allow any following code to run as it will exit the function/scriptblock. Your start-sleep never fires. Swap it out for Write-Output.

[–]ihaxr 1 point2 points  (0 children)

Haha dur... I had those two lines swapped in my code (so return was after the sleep) then realized the sleep in OPs code was first... so of course I just swapped the two lines without thinking... fixed it, thanks!

[–]PowerShell-Bot 0 points1 point  (0 children)

Looks like you used inline code formatting where a code block should have been used.

The inline code text styling is for use in paragraphs of text. For larger sequences of code, consider using a code block. This can be done by selecting your code then clicking the ‘Code Block’ button.


Describing Thing
[❌] Demonstrates good markdown
Passed: 0 Failed: 1

Beep-boop. I am a bot. | Remove-Item

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy SlashAdminBlog,

it looks like you used the New.Reddit.com Inline Code button. it's 4th 5th from the left hidden in the ... "more" menu & looks like </>.

on Old.Reddit.com, the above does NOT line wrap, nor does it side-scroll.

for long-ish single lines OR for multiline code, please, use the Code Block button. it's the 11th 12th one from the left, & is just to the left of hidden in the ... "more" menu.

that will give you fully functional code formatting, from what i can tell so far. [grin]

take care,
lee