1

我有一个复杂的 PowerShell 函数,我想运行另一个线程。

但是,如果我是对的,则无法在脚本块中访问该函数。我想避免复制它旁边的每个相关功能。

有什么方法或方法可以调用脚本块中的函数吗?

function Function1 {
    Param()
    Process {
        $param1 = "something"
        $pool = [RunspaceFactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS + 1)
        $pool.ApartmentState = "MTA"
        $pool.Open()
        $runspaces = @()

        $scriptblock = {
            Param (
                [Object] [Parameter(Mandatory = $true)] $param1
            )
            Complex_Function -param1 $param1
        }

        1..10 | ForEach-Object {
            $runspace = [PowerShell]::Create()
            $null = $runspace.AddScript($scriptblock)
            $null = $runspace.AddArgument($param1)
            $runspace.RunspacePool = $pool
            $runspaces += [PSCustomObject]@{ Pipe = $runspace; Status = $runspace.BeginInvoke() }
        }

        while ($runspaces.Status -ne $null) {
            $completed = $runspaces | Where-Object { $_.Status.IsCompleted -eq $true }
            foreach ($runspace in $completed) {
                $runspace.Pipe.EndInvoke($runspace.Status)
                $runspace.Status = $null
            }
        }

        $pool.Close()
        $pool.Dispose()
    }
}

function Complex_Function {
    Param(
        [Object] [Parameter(Mandatory = $true)] $param1
    )
    Process {
        #several function calls 
    }
}
4

1 回答 1

1

我认为在这篇博文中找到的代码可能就是你要找的:

Function ConvertTo-Hex {
    Param([int]$Number)
    '0x{0:x}' -f $Number
}

#Get body of function
$Definition = Get-Content Function:\ConvertTo-Hex -ErrorAction Stop

#Create a sessionstate function entry
$SessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry 
    -ArgumentList 'ConvertTo-Hex', $Definition

#Create a SessionStateFunction

$InitialSessionState.Commands.Add($SessionStateFunction)

 #Create the runspacepool by adding the sessionstate with the custom function

$RunspacePool = [runspacefactory]::CreateRunspacePool(1,5,$InitialSessionState,$Host)

对您的 Complex_Function 和(我猜)您需要的所有其他功能做类似的事情,它们应该可供您的运行空间使用。

编辑 您在评论中询问如何收集所有功能。路径function:/可以像目录一样被遍历和搜索,因此get-chiditem function:/可以获取所有当前定义的函数。

在对此进行试验时,似乎在当前脚本中或从点源脚本中定义的函数具有一个空Source属性。玩这个。它应该导致你想要的。

$InitialSessionState = [initialsessionstate]::Create()

Get-ChildItem function:/ | Where-Object Source -like "" | ForEach-Object {
    $functionDefinition = Get-Content "Function:\$($_.Name)"
    $sessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry `
        -ArgumentList $_.Name, $functionDefinition 
    $InitialSessionState.Commands.Add($sessionStateFunction)
}
于 2018-08-13T10:51:52.207 回答