gpt4 book ai didi

powershell - 如何在传递给函数的Powershell中附加字符串

转载 作者:行者123 更新时间:2023-12-03 00:53:43 26 4
gpt4 key购买 nike

我有一个将字符串作为参数的方法。该字符串与值连接。在处理结束时,我需要完整的串联字符串

function MyFunction()
{
Param ($output)

$msg = "x " #say this x was different per call
$output += $msg
}

$output = "start "
MyFunction -output $output
MyFunction -output $output
MyFunction -output $output

Write-Host $output

输出
"start "

预期的
"start 1 2 3 "

我使用[ref]查找,但这适用于值类型而不是引用类型。

更新

如何将不同的命名变量传递给函数,即
$output1 = "start1 "
$output2 = "start2 "

MyFunction -output $output1
MyFunction -output $output2

WriteHost($output1)
WriteHost($output2)

预期结果

从MyFunction内部附加的start1 ....
从MyFunction内部附加的start2 ...

最佳答案

在函数内部,您与脚本的其余部分不在同一范围内。
因此,在使用$ script:output更新$ output时,必须指定脚本范围:

$output= "start "
function MyFunction()
{
Param ($output)

$msg = "x " #say this x was different per call
$script:output+=$msg


}


MyFunction -output $output
MyFunction -output $output
MyFunction -output $output

Write-Host $output

关于powershell - 如何在传递给函数的Powershell中附加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14155149/

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