function - 将功能转发到新的 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
}
解决方案
局部函数仅在该范围内已知。因此,当您打开新的 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'}"
推荐阅读
- tailscale - 我什么时候应该在 Tailscale 中使用什么类型的身份验证密钥?
- c# - MSTest,我收到 result.status 代码 200 但 result.value 为空
- php - 增加共享主机中的 PHP 时间限制
- gdb - 使用vscode运行gdb时如何抑制库文件?
- sql - 使用递归 cte 获取范围内的素数列表
- json - 如何将嵌套的 JSON 转换为逗号分隔的文件进行分析?以下是详细信息
- api - SunCertPathBuilderException:无法找到请求目标的有效证书路径,.cer 文件在哪里
- haskell - 在 Haskell 中使用递归方案解决变更问题
- bash - AWK 根据 file1 中的部分标题匹配选择 file2 中的列
- r - 理解 R 中的 seq_len