gpt4 book ai didi

variables - 模块函数中使用的 $_ 变量为空 (PowerShell)

转载 作者:行者123 更新时间:2023-12-02 22:13:59 27 4
gpt4 key购买 nike

这里有一个问题要问你;)

我有这个功能:

function Set-DbFile {
param(
[Parameter(ValueFromPipeline=$true)]
[System.IO.FileInfo[]]
$InputObject,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[scriptblock]
$Properties
)
process {
$InputObject | % {
Write-Host `nInside. Storing $_.Name
$props = & $Properties
Write-Host ' properties for the file are: ' -nonew
write-Host ($props.GetEnumerator()| %{"{0}-{1}" -f $_.key,$_.Value})
}
}
}

查看$Properties。应该对每个文件进行评估,然后进一步处理该文件和属性。

如何使用它的示例可能是:

Get-ChildItem c:\windows |
? { !$_.PsIsContainer } |
Set-DbFile -prop {
Write-Host Creating properties for $_.FullName
@{Name=$_.Name } # any other properties based on the file
}

当我将函数 Set-dbFile 复制并粘贴到命令行并运行示例代码片段时,一切都很好。

但是,当我将函数存储在模块中、导入它并运行示例时,$_ 变量为空。有人知道为什么吗?以及如何解决呢? (也欢迎其他解决方案)

<小时/>

在脚本中定义的函数的结果/在命令行中键入的函数的结果:

Inside. Storing adsvw.ini
Creating properties for C:\windows\adsvw.ini
properties for the file are: Name-adsvw.ini

Inside. Storing ARJ.PIF
Creating properties for C:\windows\ARJ.PIF
properties for the file are: Name-ARJ.PIF
....

模块中定义的函数的结果:

Inside. Storing adsvw.ini
Creating properties for
properties for the file are: Name-

Inside. Storing ARJ.PIF
Creating properties for
properties for the file are: Name-
....

最佳答案

这里的问题在于范围层次结构。如果您定义两个函数,例如...

function F1{
$test="Hello"
F2
}
function F2{
$test
}

然后 F2 将继承 F1 的变量作用域,因为它是从 F1 的作用域调用的。如果您在模块中定义函数 F2 并导出该函数,则 $test 变量不可用,因为该模块有自己的作用域树。请参阅Powershell Language Specification (第 3.5.6 节):

在您的情况下,当前节点变量是在本地作用域中定义的,因此它不会存在于模块作用域中,因为它位于具有不同作用域根的不同树中(除了全局变量之外)。

引用 Powershell Language Specification 中关于 GetNewClosure() 方法的文本(第 4.3.7 节):

Retrieves a script block that is bound to a module.Any local variables that are in the context of the caller will be copied into the module.

...因此 GetNewClosure() 很有效,因为它弥合了本地范围/模块的鸿沟。我希望这会有所帮助。

关于variables - 模块函数中使用的 $_ 变量为空 (PowerShell),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6264374/

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