Search code examples
functionpowershellinvoke-command

forward function to new powershell session or use Invoke-command?


I have below command, that I want to be called from my script, how can I pass the function New-PopupMessage ?

Start-Process $PSScriptRoot\ServiceUI.exe 
-process:TSProgressUI.exe %SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe 
-noprofile -windowstyle hidden -executionpolicy bypass  -command New-PopupMessage @Params

I also tried with a Invoke-command

Invoke-Command -ScriptBlock {
Start-Process $PSScriptRoot\ServiceUI.exe 
-process:TSProgressUI.exe %SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe 
-noprofile -windowstyle hidden -executionpolicy bypass 
-command ${function:New-PopupMessage} -ArgumentList @Params
 }

Solution

  • Local functions are only known in that scope. A function defined in a script is therefore not known when you open a new powershell process. You could create a module so your function will be available for other scripts / powershell sessions. Or maybe this 'hack' will work for you. This example will pass the local function to a new powershell session. This solution will only work for "simple" functions. See also the comment from mklement0. He recommends the following link: Run PowerShell custom function in new window

    function New-PopupMessage
    {
        param
        (
            [System.String]$P1,
            [System.String]$P2
        )
    
        Out-Host -InputObject ('Output: ' + $P1 + ' ' + $P2)
    }
    
    New-PopupMessage -P1 'P1' -P2 'P2'
    
    
    $Function = Get-Command -Name New-PopupMessage -CommandType Function
    
    Start-Process -FilePath powershell.exe -ArgumentList '-noexit', "-command &{function $($Function.Name) {$($Function.ScriptBlock)}; $($Function.Name) -P1 'P1' -P2 'P2'}"