2

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
 }
BenDK
  • 131
  • 2
  • 7
  • 3
    The code you posted is broken. Please do not wrap code in arbitrary places. – Ansgar Wiechers Oct 22 '19 at 12:39
  • 1
    Can you use a script instead of a function? This comes up in jobs and foreach -parallel too. – js2010 Oct 22 '19 at 15:27
  • Well I have it working by calling a script with ServiceUI.exe, but I want to reuse the code therefor a function, ServiceUI needed in order to run the script in user context – BenDK Oct 23 '19 at 06:44
  • Patricks Solution is working for me, I will try to combine it with @mklement0 link – BenDK Oct 23 '19 at 06:45

1 Answers1

3

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'}"
Patrick
  • 2,128
  • 16
  • 24
  • Nicely done, but while your specific function definition works, the solution isn't _robust_, because `"` chars. in the function definition break it, as may `\ ` instances. Unfortunately, the solution isn't as simple as applying `-replace '["\\]', '\$&'` first, as I initially thought, because it wouldn't work properly with a function such as `function New-PopupMessage { "arguments: \$args\"; gi c:\ }`, for instance. See https://stackoverflow.com/a/44986341/45375 – mklement0 Oct 22 '19 at 14:37