将函数放在单独的脚本中并对它们进行点源 - 范围是什么

Sun*_*une 11 powershell scope function

我把我的函数放在一个单独的文件中,然后调用该文件:

$workingdir = Split-Path $MyInvocation.MyCommand.Path -Parent
. "$workingdir\serverscan-functions.ps1"                        
Run Code Online (Sandbox Code Playgroud)

但是,如果我把脚本称为

my-function
Run Code Online (Sandbox Code Playgroud)

变量范围(来自"my-function")将如何?我还应该使用$ script:变量来使变量存在于函数外部还是我也可以点源函数?

希望我不要把任何人与我的问题混淆......我试图让它尽可能地理解,但仍然学习所有的基本概念,所以我觉得很难解释..

And*_*ndi 21

当您点源代码时,它的行为就像该代码仍在原始脚本中一样.范围将与在一个文件中全部相同.

C:\ functions.ps1代码:

$myVariable = "Test"

function Test-DotSource {
    $script:thisIsAvailableInFunctions = "foo"
    $thisIsAvailableOnlyInThisFunction = "bar"
}
Run Code Online (Sandbox Code Playgroud)

main.ps1代码

$script:thisIsAvailableInFunctions = ""

. C:\functions.ps1

# Call the function to set values.
Test-DotSource

$script:thisIsAvailableInFunctions -eq "foo" 
# Outputs True because of the script: scope modifier

$thisIsAvailableOnlyInThisFunction -eq "bar" 
# Outputs False because it's undefined in this scope.

$myVariable -eq "Test"                       
# Outputs true because it's in the same scope due to dot sourcing.
Run Code Online (Sandbox Code Playgroud)

  • @Sune 我用一些例子更新了我的答案。希望它有帮助。 (2认同)