gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:05:18 24 4
gpt4 key购买 nike

我将函数放在一个单独的文件中,并使用以下命令调用该文件:

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

但是,如果我这样调用脚本

my-function

变量范围(来自“my-function”内)如何?我是否仍然应该使用 $script:variable 来使变量存在于函数外部,或者是否也对函数进行点源化?

希望我不会让任何人对我的问题感到困惑...我已尽力使其尽可能易于理解,但仍在学习所有基本概念,因此我发现很难解释...

最佳答案

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

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.

关于function - 将函数放在单独的脚本中并对它们进行点采购 - 范围是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9384112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com