首页 > 解决方案 > 将功能转发到新的 powershell 会话或使用调用命令?

问题描述

我有以下命令,我想从我的脚本中调用,我该如何传递函数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

我也尝试过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
 }

标签: functionpowershellinvoke-command

解决方案


局部函数仅在该范围内已知。因此,当您打开新的 powershell 进程时,脚本中定义的函数是未知的。您可以创建一个模块,以便您的函数可用于其他脚本/powershell 会话。或者也许这个“黑客”对你有用。此示例将本地函数传递给新的 powershell 会话。此解决方案仅适用于“简单”功能。另请参阅 mklement0 的评论。他推荐以下链接:在新窗口中运行 PowerShell 自定义函数

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'}"

推荐阅读