Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an array variable that is passed by reference

Tags:

powershell

I have an array object variable as [ref] $InsertColHeadName = @() in a function and then call another function with param ([ref] $InsertColHeadName). In the called function I then tried refering to my parameter set in param ([ref] $InsertColHeadName) += expression. The expression returns a string. I placed a breakpoint in the line and tried forcing a string with single quotes eg.: ([ref] $InsertColHeadName) += 'xyz';.

I tried googling around but can't seem to find a suitable solution.

I am getting the following error:

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 not
contain a method named 'op_Addition'.
At line:1 char:1
+ ([ref] $InsertColHeadName) += 'DepartmentNo';
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
like image 914
Costa Zachariou Avatar asked Mar 16 '26 15:03

Costa Zachariou


2 Answers

Inside the function the InsertColHeadName is already a reference. Adding [ref] to it creates a reference of the reference.

instead try :

$InsertColHeadName.Value += expression

Here is an example:

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

The output:

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
like image 125
Pankaj Avatar answered Mar 22 '26 05:03

Pankaj


Had this same issue. Just have to make sure you do not cast the object to [ref] multiple times. It's like casting [ref][ref][ref]$YourObject.

like image 29
BrandonMFong Avatar answered Mar 22 '26 07:03

BrandonMFong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!