Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function 访问函数执行后在函数内创建的变量_Function_Variables_Powershell - Fatal编程技术网

Function 访问函数执行后在函数内创建的变量

Function 访问函数执行后在函数内创建的变量,function,variables,powershell,Function,Variables,Powershell,我正在使用一个函数,它创建了一些我想在函数处理后使用的变量。 我试过直接访问它们,但我不能。我该怎么做呢?函数中的变量在函数运行后无法继续存在。如果要在函数处理后访问它们,请在它们前面加上范围修饰符 PS> function test-var{ $script:var='foo' } PS> test-var # excute the function PS> $var #print var foo 有关详细信息,请在控制台中键入: PS> Get-Help about

我正在使用一个函数,它创建了一些我想在函数处理后使用的变量。
我试过直接访问它们,但我不能。我该怎么做呢?

函数中的变量在函数运行后无法继续存在。如果要在函数处理后访问它们,请在它们前面加上范围修饰符

PS> function test-var{ $script:var='foo' }
PS> test-var # excute the function
PS> $var #print var
foo
有关详细信息,请在控制台中键入:

PS> Get-Help about_Scopes

正如Shay指出的,您可以在函数范围内创建所谓的全局变量,这些变量将在更高级别的范围内可用。然而,全局变量通常不是一个好主意,我想为您推荐一些替代方案

这来自维基百科页面:

他们通常被认为是不好的做法,正是因为他们的缺点 非局部性:全局变量可以从 任何位置(除非它们位于受保护的内存中或其他位置) 呈现为只读),程序的任何部分都可能依赖于它。[1] 因此,全局变量具有无限的创建 相互依赖,增加相互依赖会增加 复杂性

一些备选方案:

  • 使函数返回调用方所需的数据。Powershell函数通常应返回与动词-名词的Powershell函数中的名词相关的数据。如果需要返回与名词无关的其他数据,请考虑做第二个函数。< /P>
    function Get-Directories {
        param ([string] $Path)
    
        # Code to get or create objects here.
        $dirs = Get-ChildItem -Path $Path | where {$_.PsIsContainer}
    
        # Explicitly return data to the caller.
        return $dirs
    }
    
    $myDirs = Get-Directories -Path 'C:\'
    
  • 使用一个。引用将变量在内存中的地址传递给函数。当函数更改变量的数据时,可以在函数外部访问变量,但变量的范围不会更改

    function Get-Directories {
        param ([string] $Path, [ref] $Directories)
        $Directories.Value = Get-ChildItem -Path $Path | where {$_.PsIsContainer}
    }
    
    $myDirs = $null
    Get-Directories -Path 'C:\' -Directories ([ref] $myDirs)
    

希望这有帮助。快乐编码:-)

如果使用运行函数,函数将在您的作用域中执行,并且函数中定义的所有变量都将对调用方可用

i、 e

如果函数在模块中,您还可以使用以下技巧访问模块的作用域:

$m  =Get-Module myModule
. $m { $myPrivateModuleVariable  }

希望这有帮助

你能分享源代码吗?谢谢你的深思熟虑的回答!非常感谢。但是为什么在函数前面有一个美元符号呢?就像一个变量?因为它是一个示例:-),不过,您也可以这样处理命令。即$a=获取命令获取命令;&$a、 或者脚本块:$a={$b=1}$a$B
$m  =Get-Module myModule
. $m { $myPrivateModuleVariable  }