PowerShell,从其他 PS 脚本调用函数并返回对象
如何从其他 PowerShell 脚本调用函数并返回对象?
主脚本:
# Run function script
. C:\MySystem\Functions.ps1
RunIE
$ie.Navigate("http://www.stackoverflow.com")
# The Object $ie is not existing
函数脚本:
function RunIE($ie)
{
$ie = New-Object -ComObject InternetExplorer.Application
}
How it is possible to call a function from a other PowerShell script an returning the object?
Main Script:
# Run function script
. C:\MySystem\Functions.ps1
RunIE
$ie.Navigate("http://www.stackoverflow.com")
# The Object $ie is not existing
Functions Script:
function RunIE($ie)
{
$ie = New-Object -ComObject InternetExplorer.Application
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需从函数中“输出”对象,如下所示:
或更惯用的
是然后将输出分配给主脚本中的变量:
Just "output" the object from the function like so:
or more idiomatically
Then assign the output to a variable in your main script:
Keith 提供了解决您问题的最佳答案。无论如何,我想添加一些内容以使答案更完整。
如果你的函数是这样定义的:
那么它只是在函数
RunIE
的范围内创建新变量并在其中分配一些东西。函数完成后,$ie
变量将被丢弃。在某些情况下(我将其用于某种类型的调试),您可能需要在当前范围内执行函数,这称为“点源”。只要尝试谷歌,你就会看到。
Keith provided the answer that is the best solution for your problem. Anyway, I'd like to add something to have the answer more complete.
If your function is defined like this:
then it just creates new variable in scope of function
RunIE
and assigns something in it. After the function completes, the$ie
variable is discarded.In some cases (I use it for some type of debugging), you might need to execute function in the current scope and that is known as `dot sourcing'. Just try Google and you will see.