从运行空间内的模块调用函数 [英] Call function from module inside a runspace
问题描述
我想从运行空间调用模块中的一些函数,但它不起作用.我假设我必须以某种方式将模块发送到运行空间.
I have some functions in a module I would like to call from a runspace but It´s not working. I assume that I somehow have to send the module to the runspace.
下面的例子工作正常.
$hash = [hashtable]::Synchronized(@{})
$hash.OutData
$runspace = [runspacefactory]::CreateRunspace()
$runspace.Open()
$runspace.SessionStateProxy.SetVariable('Hash',$hash)
$powershell = [powershell]::Create()
$powershell.Runspace = $runspace
$powershell.AddScript({
$hash.OutData = Get-Date
}) | Out-Null
$handle = $powershell.BeginInvoke()
While (-Not $handle.IsCompleted) {
Start-Sleep -Milliseconds 100
}
$powershell.EndInvoke($handle)
$runspace.Close()
$powershell.Dispose()
但是,如果我像这样调用自己的函数,则 OutData 为空.该函数在运行空间之外工作正常.
But if I call my own function instead like this, the OutData is blank. The function works fine outside of the runspace.
$powershell.AddScript({
$hash.OutData = Get-customData
}) | Out-Null
我需要做什么才能调用我的函数?
What do I have to do be able to call my function?
推荐答案
如果您的模块不在 $env:PSModulePath
中列出的目录之一中(或者后一个环境变量不在定义,如果您在外部可执行文件中托管 PowerShell SDK,这可能会在 Unix 上发生),您必须显式地导入它:
If your module isn't in one of the directories listed in $env:PSModulePath
(or the latter environment variable isn't defined, which could happen on Unix if you're hosting the PowerShell SDK in an external executable), you must import it explicitly:
$yourFullModulePath = '<your-full-module-path-here>'
# Create a default session state and import a module into it.
$iss = [InitialSessionState]::CreateDefault()
$iss.ImportPSModule($yourFullModulePath)
# Create the runspace with the initial session state and open it.
$runspace = [runspacefactory]::CreateRunspace($iss)
$runspace.Open()
# Create a PowerShell instance and assign the runspace to it.
$powershell = [powershell]::Create($runspace)
# ...
请注意,您可以利用 [powershell]
实例自动创建运行空间这一事实来简化代码:
Note that you can simplify your code by taking advantage of the fact that a [powershell]
instance automatically creates a runspace:
# Pass the initial session state directly to [powershell]::Create(),
# which automatically provides a runspace.
$powershell = [powershell]::Create($iss)
# Access the [powershell] instance's runspace via the `.Runspace` property.
$powerShell.Runspace.SessionStateProxy.SetVariable('Hash', $hash)
# ...
这篇关于从运行空间内的模块调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!