How to pass parameter by reference?

Hello,

I am just wondering how to pass a parameter reference without [ref] prefix to the variable in the runtime. For example…

[pre]

$a = 10

$a | Add-One

$a

Output

<hr />

11

[/pre]

The Add-One script is as follows…

[pre]

Function Add-One
{
param
(
[parameter(Mandatory,ValueFromPipeline)]
[ref]$Obj
)
$Obj.Value += 1
}
[/pre]
The above function works when you call the funtion with [ref] prefix...
[pre]
[ref]$a | Add-One
$a
Output
--------
11
[/pre]
But I want the function should handle the referance. Any help? Thank you.

Is this what you’re looking for:

To pass a variable to a parameter that expects a reference, you must type cast your variable as a reference.
From https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_ref?view=powershell-6

(under Writing functions to accept reference parameters)

Yeah, I have seen this as well, but I am trying to achieve this in the runtime without mentioning the [ref] explicitly. I want something like this…

[pre]

$a = 10

$a | Add-One

$a

[/pre]

The output should be 11.

I have achieved this using [ref] explicitly, as mentioned in the function above.

Can’t be done in this way, I’m afraid! [ref] is required. :slight_smile:

A bare value like 10 is just a number. You can’t “modify” that number itself, you can only modify the variable’s value. So if you want to affect the value of the variable itself, you have to pass a reference to the variable and not its value, which is what [ref] does. And yeah, you have to pass it explicitly with [ref] or pass it a variable that itself stores a reference to another variable.

Do you have a more fully fleshed out use case you intend for this design? PowerShell isn’t really designed around frequent use of [ref] and it’s not a pattern I would generally recommend using in the vast majority of cases. Nearly always it’s best to just return the value from the function.

Yeah, even I did little research, but couldn’t figure it out.

This a special requirement from one of our clients as part of a temporary workaround for one of the processes.

Thank you.