Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell passing two arrays by reference to a function

At the moment I am trying to pass in two array items by reference to a function I have written which loads data into those arrays. However, once this function loses scope the arrays appear as blank.

If I use the ref keyword to pass them into the function the first array loads up correctly. However, the second array gives an error saying that I cannot use the add operator on it.

$logConfigPath = "C:\Testing\Configuration\config.xml"

#### VARIABLES RELATING TO THE LOG FILE

# Contains the log path and log file mask
$logPaths = @()
$logFileMasks = @()

#### FUNCTION CALLS
LoadLogTailerConfig($logConfigPath, $logPaths, $logFileMasks)

"$logPaths"
"$logFileMasks"


function LoadLogTailerConfig($logConfigPath, $logPath, $logFileMasks)
{
    Write-Debug "Loading config file data from $logConfigPath"

    [xml]$configData = Get-Content "C:\Testing\Configuration\config.xml"

    foreach ($log in $configData.Logs.Log) {

        $logPaths += $log.FilePath
        $logFileMasks += $log.FileMask
    }
}

Why is this not working for me?

like image 490
Matthew Pigram Avatar asked Feb 03 '15 03:02

Matthew Pigram


1 Answers

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 CALLS
LoadLogTailerConfig $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

like image 149
Andrew Savinykh Avatar answered Nov 03 '22 03:11

Andrew Savinykh