powershell 如何将一个'using namespace'传递给正在调用函数的start-threadjob?

64jmpszr  于 2023-04-06  发布在  Shell
关注(0)|答案(1)|浏览(109)

问题:

我有一个使用Start-ThreadJob调用的函数,该函数需要以下命名空间才能使用:

using namespace System.Diagnostics.Eventing.Reader

我如何让这个函数看到它?

深度潜水:

代码有点复杂,但我生成了一个用于派生线程的对象的队列列表,函数名是标记,这是正在调用的实际函数。我的问题是,代码不识别脚本顶部声明的名称空间,所以我相信它必须以某种方式传递给函数线程?

代码示例(有点复杂):

Function MyFunctionName { Write-Host("Hello World") }

     $Queue += [pscustomobject]@{
        Tag = 'MyFunctionName'  # Function to Invoke here
     }

    $commandDefinitions = @{}
    $WorkerJobs = foreach ($Task in $Queue) {
        # If we already have the Definition for this Action
        if ($commandDefinitions.ContainsKey($Task.Tag)) {
            $def = $commandDefinitions[$Task.Tag]  # use it
        }
        else {
            # else, get it and set it
            $def = (Get-Command $Task.Tag -CommandType Function).Definition
            $commandDefinitions[$Task.Tag] = $def
        }
        
        Start-ThreadJob { 
            & ([scriptblock]::Create($using:def)) @Using:Task 
        }
        
    }
yhuiod9q

yhuiod9q1#

简短的回答是,你不应该这样做,因为这个解决方案既不漂亮也不可靠。你应该在线程的脚本块中使用类型完全限定名。为了演示起见,这里是你如何做到这一点:

$usingStatements = @'
using namespace System.Diagnostics.Eventing.Reader
using namespace System.Collections.Generic
'@

function Test {
    [EventLogReader]
    [EventLogQuery]
    [List[object]]
}

$func = ${function:Test}.ToString()

Start-ThreadJob {
    . ([scriptblock]::Create($using:usingStatements))

    ${function:Test} = $using:func

    Test
} | Receive-Job -Wait -AutoRemoveJob

相关问题