繁体   English   中英

PowerShell,不能 append function 中的变量

[英]PowerShell, cannot append a variable inside a function

我对 PowerShell 中的某些内容感到有点困惑。

在 function 的末尾,它向变量附加了一些文本,以便我可以记录发生的事情。 但是当我这样做时,$x 只包含 header 而没有其他内容。 我究竟做错了什么?

$x = "Header`n=========="

function xxx ($z) {
    $z = "$z ... 1"
    $x += "`noutput from $z"
}

xxx 123
xxx 234
xxx 345
xxx 456

总结评论,并参考@mklement0 的类似问题的回答 - https://stackoverflow.com/a/38675054/3156906 - 默认行为是 PowerShell 让你从父 scope读取变量,但如果您分配一个值,它会在子变量 scope 中创建一个新变量,该变量“隐藏”父变量,直到子变量 scope 存在。

about_Scopes文档也说了类似的话,但不幸的是并没有真正详细说明:

如果您在 scope 中创建一个项目,并且该项目与另一个 scope 中的项目共享其名称,则原始项目可能隐藏在新项目下,但不会被覆盖或更改。

如果您通过 scope 数字明确引用它,则可以为父 scope 中的变量赋值 - 例如:

$x = "some value"

function Invoke-MyFunction
{
    # "-Scope 1" means "immediate parent scope"
    Set-Variable x -Value "another value" -Scope 1
}

Invoke-MyFunction

write-host $x

但是,在您的情况下,您可能希望将日志记录逻辑包装到单独的函数中,而不是用大量的Set-Variable x -Value ($x + "another log line") -Scope 1 (这是一个实现细节)您的日志记录方法)。

每次您添加一些日志记录 output 时,您当前的方法都会通过创建一个新的(并且越来越长的)字符串 object 来降低性能,并且它也会使得以后很难更改您的日志记录机制(例如,如果您决定怎么办想改为记录到文件?),因为您需要 go 返回到每个记录行并重写它以使用新机制。

你可以做的是这样的:

记录代码

$script:LogEntries = new-object System.Collections.ArrayList; 

function Write-LogEntry
{
    param( [string] $Value )
    $null = $script:LogEntries.Add($Value)
}

function Get-LogEntries
{
    return $script:LogEntries
}

申请代码

function Invoke-MyFunction
{
    Write-LogEntry -Value "another logging line"
}

然后你的日志记录机制从你的主应用程序中抽象出来,你的应用程序只需要调用Write-LogEntry

请注意, $script:<varname>是使用Scope 修饰符在包含脚本的根 scope 中引用变量的另一种方式 - 该链接描述了一些其他选项,包括globallocalprivate

暂无
暂无

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

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