问题:
我有一个使用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
}
}
1条答案
按热度按时间yhuiod9q1#
简短的回答是,你不应该这样做,因为这个解决方案既不漂亮也不可靠。你应该在线程的脚本块中使用类型完全限定名。为了演示起见,这里是你如何做到这一点: