Hansson0728
Hansson0728

Reputation: 28

Powershell start-process Runspace wont start except with -noexit flag

So i wrote this little GUI with Runspaces. it works as expected when running it in ISE, and if i start it from a PS prompt, but when i try to run it from a Shortcut it just wont boot as long as i dont use the -noexit flag. but when using the -noexit flag it will leave the Powershell process running even after i close the GUI.

iam using this tecnuiqe for my GUI: Powershell GUI Template

this is what i have in my shortcut: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -sta -WindowStyle Hidden -file "C:\Temp\Runspaceversion.ps1"

that wont work... but if i do

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -sta -WindowStyle Hidden -noexit -file "C:\IT\Checklist\Runspaceversion.ps1"

it works, but i get the powershell process idling when i exit the Gui....

Upvotes: 0

Views: 819

Answers (3)

Hansson0728
Hansson0728

Reputation: 28

I managed to get around it, with passing a Paramater with $PID killing both the session that started the GUI and as Postnote said, killing the process when exiting the GUI.

Upvotes: 0

postanote
postanote

Reputation: 16096

There is no exit code in the template being used.

When the Window is closed, this fires...

    #region Window Close 
    $syncHash.Window.Add_Closed({
        Write-Verbose 'Halt runspace cleanup job processing'
        $jobCleanup.Flag = $False

        #Stop all runspaces
        $jobCleanup.PowerShell.Dispose()

    })

Change that block to include something like this...

    #region Window Close 
    $syncHash.Window.Add_Closed({
        Write-Verbose 'Halt runspace cleanup job processing'
        $jobCleanup.Flag = $False

        #Stop all runspaces
        $jobCleanup.PowerShell.Dispose()
        $jobProcessInfo = (Get-WmiObject win32_process `
        -Filter {name = 'powershell.exe' and commandline like '%PowerShell_GUI_Template.ps1%'})
        Stop-Process -Id $jobProcessInfo.ProcessId

    })

Of course this may be a brute force way of doing this, but I pulled down the template and this works for closing the associated host process on the closing the form Window.

This is what I have in the shortcut.

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -noexit "& { D:\Scripts\PowerShellTips\PowerShell_GUI_Template.ps1 }

Upvotes: 0

Deadly-Bagel
Deadly-Bagel

Reputation: 1620

The problem is by default the PowerShell console closes, also terminating all associated runspaces and threads including the one of the form it just created. This is because BeginInvoke() starts the form but then resumes the current thread.

Basically PowerShell has to be running. Instead of BeginInvoke() you could try RunDialog() which will hold the main thread until the Form is closed, at which point PowerShell will also exit.

Upvotes: 0

Related Questions