gpt4 book ai didi

powershell - 设置通过引用传递的数组变量

转载 作者:行者123 更新时间:2023-12-02 23:57:44 25 4
gpt4 key购买 nike

我在函数中有一个数组对象变量作为 [ref] $InsertColHeadName = @(),然后使用 param ([ref] $InsertColHeadName) 调用另一个函数.然后在被调用的函数中,我尝试引用参数 ([ref] $InsertColHeadName) += expression 中的参数集。表达式返回一个字符串。我在行中放置了一个断点并尝试强制使用单引号的字符串,例如:([ref] $InsertColHeadName) += 'xyz';

我试过谷歌搜索,但似乎找不到合适的解决方案。

我收到以下错误:

Method invocation failed because [System.Management.Automation.PSReference`1[[System.Management.Automation.PSReference`1[[System.Management.Automation.PSReference`1[[System.Object[], mscorlib, Version=4.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089]], System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]] does notcontain a method named 'op_Addition'.At line:1 char:1+ ([ref] $InsertColHeadName) += 'DepartmentNo';+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException    + FullyQualifiedErrorId : MethodNotFound

最佳答案

在函数内部,InsertColHeadName 已经是一个引用。向其添加 [ref] 创建引用的引用。

改为尝试:

$InsertColHeadName.Value += expression

这是一个例子:

function AddMe([ref]$array)
{
$array.value += 40
}

$x = @(1..10)

Write-Host Before Calling AddMe $x
AddMe ([ref]$x)
Write-Host After Calling AddMe $x

输出:

Before Calling AddMe 1 2 3 4 5 6 7 8 9 10
After Calling AddMe 1 2 3 4 5 6 7 8 9 10 40

关于powershell - 设置通过引用传递的数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39353277/

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