PowerShell passing two arrays by reference to a function PowerShell passing two arrays by reference to a function arrays arrays

PowerShell passing two arrays by reference to a function


I modified your example to work:

$logConfigPath = "C:\Testing\Configuration\config.xml"#### VARIABLES RELATING TO THE LOG FILE# Contains the log path and log file mask$logPaths = @()$logFileMasks = @()function LoadLogTailerConfig($logConfigPath, [ref]$logPaths, [ref]$logFileMasks){    Write-Debug "Loading config file data from $logConfigPath"    #[xml]$configData = Get-Content "C:\Testing\Configuration\config.xml"    foreach ($log in 1..10) {        $logPaths.value += $log        $logFileMasks.value += $log    }}#### FUNCTION CALLSLoadLogTailerConfig $logConfigPath ([ref]$logPaths) ([ref]$logFileMasks)"$logPaths""$logFileMasks"

Notes:

  • Different syntax for calling functions in PowerShell
  • You need to define your function first then call not the other way around
  • Make sure that you use correct parameter names. Your functions accept $logPath, but then it tries to modify $logPaths - of course that's not going to work as expected because of the extra s at the end
  • You need to use [ref] both in the function definition and function call
  • You need to access reference value by adding .value to the reference variable

Also refer to the almost identical prior question here: Powershell passing argument values to parameters and back


You are complaining about a problem that's not the first problem in your code. You are using the function LoadLogTrailerConfig without defining it before its usage. So, you must correct this gaffe first. After the correction, your code will run without syntax error, but logically it will still present an undesired output, but the explanation will then, be simple: array is an imutable reference object.