Call functions in events don't work if -AsJob

Feb 9, 2014 at 10:31 PM
Edited Feb 12, 2014 at 8:31 AM
Hello!
Perhaps a simple question.
I have own function declarations in the same powershell script.

Calling these own functions works only in -show mode
in -AsJob mode the function names are unknown
even if the functions are declared with global scope.
Import-Module ShowUi
function global:Afunc ( ) { #function is unknown in the event routine
    return ( "String from function" )
}

New-Label -name lbl -FontSize 24 -Content "Original Unbound Content"  `
        -On_MouseDoubleClick {
            $This.Content =  AFunc
        } -AsJob
I wanted to choose the mode -AsJob because
I had troubles to start the script in the -show mode
using PowerShell 2.0
Meanwhile I read about the -STA option and
have a good solution with the batch command:
@echo off
cd /D C:\Users\Public\Documents
start powershell -STA -WindowStyle Hidden -Command .\MyPoShScript.ps1
Thank you for discussion
Erhy
Feb 12, 2014 at 12:15 PM
Edited Feb 14, 2014 at 2:20 PM
I see that methods can be added to PowerShell object variable with Add-Member.
So I put the function to a variable with a wide scope.
With powershell-ise the app runs without problem,
but if I want to start it with a batch script I get the error
New-Label : The term 'Get-ReferencedCommand' is not recognized as the name of a cmdlet, ...
Next I adited Microsoft.PowerShell_profile.ps1 and inserted the line
import-module ShowUI
the error gone, but the windows task had only a life for 1 second.
This all with PowerShell 2.0 on VISTA
Import-Module ShowUi
New-Label -name lbl -FontSize 24 -Content 'Original Unbound Content' `
    -On_MouseDoubleClick {
        Add-Member -InputObject $lbl -MemberType ScriptMethod -Name 'Afunc' -Value {
            param ([int]$len)
            return ( "String from function with value " + $len )
        }
        $This.Content =  $lbl.AFunc( 2 )
    } -AsJob > $null
Coordinator
Feb 14, 2014 at 4:47 PM
If you start a ShowUI with -AsJob it starts a background job and then returns (to the prompt).

If you're using a script that just creates a background job as the "command" for a new PowerShell.exe like you have listed above, then PowerShell will exit right away. Unfortunately, when PowerShell exits, it cleans up all the background jobs -- including the one you were trying to use to create your UI. You can probably see that if you add a Start-Sleep -Seconds 30 at the bottom of your script file: that would make sure it had time to create and display the UI for a little while before PowerShell exits and closes it.

You should change that to -Show if you're going to run it that way ... -AsJob is for when you're in the console and you want control back to the console while the UI runs.
Marked as answer by Erhy on 2/15/2014 at 1:48 AM