Iterate over array of references

Helmut-72 66 Reputation points
2023-01-28T19:58:37.65+00:00

Hi,

I want to create a function to write a message to multiple variables. I'm trying to do this via [ref]:

function My-Write-Output () {
	[CmdletBinding()]
		Param(
			[Parameter(Mandatory)]
				[array]$message,
			[Parameter()]
				[ref]$var
		)
	
	foreach ($line in $message) {
		foreach ($ref in $var) {
			if ($append) {
				$ref.value += "$line"
			} else {
				$ref.value = "$line"
			}
		}
	}
}

This works with 1 variable:

PS C:\Scripts> . '.\Common Helpers.ps1'; $variable1 = @(10); $variable2 = 20; My-Write-Output -message "Blub" -var ([ref]$variable1) -append;
$variable1; $variable2
10
Blub
20
PS C:\Scripts>

How can I do this with multiple variables?

PS C:\Scripts> . '.\Common Helpers.ps1'; $variable1 = @(10); $variable2 = @(20); My-Write-Output -message "Blub" -var ([ref]$variable1), ([ref
]$variable2) -append; $variable1; $variable2
My-Write-Output : Cannot process argument transformation on parameter 'var'. Reference type is expected in argument.
At line:1 char:104
+ ... put -message "Blub" -var ([ref]$variable1), ([ref]$variable2) -append ...
+                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [My-Write-Output], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,My-Write-Output

10
20
PS C:\Scripts>

Thank you!

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,282 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 44,006 Reputation points
    2023-01-29T16:51:55.4733333+00:00

    When you use the "-append" you're trying to ADD the value of $line to an integer (i.e., the VALUE of $ref). Addition requires the coercion (casting) of the STRING value of $line to an integer, and "Blub" does not represent an integer value.

    When you don't use the "-append" parameter you're REPLACING the value of $ref (e.g., 10) with the string in $line. Since PowerShell variables are untyped (unless explicitly cast as a type) the replacement doesn't require any coercion.