开发者

PowerShell, Calling a function from a other PS Script and returning a Object

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 existi开发者_如何转开发ng

Functions Script:

function RunIE($ie) 
{
$ie = New-Object -ComObject InternetExplorer.Application
}


Just "output" the object from the function like so:

function RunIE
{ 
    $ie = New-Object -ComObject InternetExplorer.Application 
    Write-Output $ie
} 

or more idiomatically

function RunIE 
{ 
    New-Object -ComObject InternetExplorer.Application 
} 

Then assign the output to a variable in your main script:

$ie = RunIE


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:

function getvars
{
    $a = 10
    $b = "b"
}

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.

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜