PowerShell,从其他PS脚本调用函数并返回对象

PowerShell,从其他PS脚本调用函数并返回对象,powershell,object,pipeline,Powershell,Object,Pipeline,如何从其他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.Appli

如何从其他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
}
只需从函数中“输出”对象,如下所示:

function RunIE
{ 
    $ie = New-Object -ComObject InternetExplorer.Application 
    Write-Output $ie
} 
或者更习惯地说

function RunIE 
{ 
    New-Object -ComObject InternetExplorer.Application 
} 
然后将输出分配给主脚本中的变量:

$ie = RunIE
Keith提供的答案是解决您问题的最佳方案。无论如何,我想补充一点,让答案更完整

如果您的函数定义如下:

function getvars
{
    $a = 10
    $b = "b"
}
然后它只是在函数
RunIE
的范围内创建新变量,并在其中赋值。函数完成后,
$ie
变量被丢弃

在某些情况下(我使用它进行某种类型的调试),您可能需要在当前范围内执行函数,这就是所谓的“点源”。只要试试谷歌,你就会明白

PS> $a = 11
PS> getvars
PS> $a, $b
11

PS> $a = 11
PS> . getvars
PS> $a, $b
10
b

要完成答案,您可以添加
。RunIE(我猜是
)。C:\MySystem\Functions.ps1
已经点源于RunIE函数。在这种情况下,
$ie=RunIE
就足够了。我的意思是“您还可以添加注意,
.RunIE
是可能的。我刚才讨论的是原始示例,其中函数看起来像
函数RunIE{$ie=..}
。哦,明白了。这看起来确实有点恶心——用这种方式将函数作用域变量提升到当前作用域?:-)我不认为这是最好的解决方案。我只添加我的注释,这样我就满意了,您不必编辑您的答案;)