微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从运行空间内的模块调用函数

如何解决从运行空间内的模块调用函数

我想从运行空间调用模块中的一些函数,但它不起作用。我假设我必须以某种方式将模块发送到运行空间。

下面的例子工作正常。

$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 为空。该函数在运行空间之外工作正常。

$powershell.AddScript({

    $hash.OutData = Get-customData

}) | Out-Null

我需要做什么才能调用我的函数

解决方法

如果您的模块不在 $env:PSModulePath 中列出的目录之一中(或者未定义后一个环境变量,如果您在外部可执行文件中托管 PowerShell SDK,这可能会在 Unix 上发生) ,您必须显式导入它:

$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] 实例自动创建运行空间这一事实来简化代码:

# 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)

# ...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?