繁体   English   中英

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

[英]Putting functions in separate script and dot-sourcing them - what will the scope be

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

$workingdir = Split-Path $MyInvocation.MyCommand.Path -Parent
. "$workingdir\serverscan-functions.ps1"                        

但是,如果我把脚本称为

my-function

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

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

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

C:\\ functions.ps1代码:

$myVariable = "Test"

function Test-DotSource {
    $script:thisIsAvailableInFunctions = "foo"
    $thisIsAvailableOnlyInThisFunction = "bar"
}

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.

为了达到你想要的效果,你可能需要创建一个模块。 在模块中,使用Export-ModuleMember导出函数,只要您没有显式地将任何变量导出为模块成员,您应该没问题。

创建模块后,使用Import-Module cmdlet Import-Module

我的2:

通常(在过去的安迪·阿里斯门迪回答之后!上帝保佑你们!)我将所有脚本保存在$pwd文件夹中(在系统路径环境中添加)。 我可以从控制台调用它们而不用点源,并且在脚本结束工作后没有脚本变量使控制台中毒。

如果你不能用简单的脚本修改你的功能(有时它会发生)我同意Trevor的回答来创建一个模块并在$profile导入它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM