Powershell:在后台调用函数,包含所有变量和对象

问题描述 投票:0回答:1

我正在尝试调用一个已定义的函数(使用声明的变量和对象)作为后台任务来改变powershell gui中的对象。

应该是这样的:

function CallFunction
{
    #call function in background        
    Start-Job {alterLabel}
}

function alterLabel
{
    $Label.text                      = "Label was altered"
}

有没有可能调用已经使用过的这个函数。所以我无法将其定义为变量,因为它会导致巨大的冗余。

powershell parallel-processing
1个回答
0
投票

你可以使用runspacepool做这样的事情:

$Runspace = [runspacefactory]::CreateRunspace()

$PowerShell = [powershell]::Create()

$PowerShell.runspace = $Runspace

$Runspace.Open()

[void]$PowerShell.AddScript({

    function alterLabel
            {
            $Label.text = "Label was altered"
            }

    alterLabel
})

$AsyncObject = $PowerShell.BeginInvoke()
$AsyncObject

根据评论,请尝试这种方法。在start-job中有一个InitializationScript参数,您可以在之前编译该函数。

$init= function alterLabel
{
    $Label.text  = "Label was altered"
}

Start-Job -InitializationScript $init -ScriptBlock {alterLabel}

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.