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?
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:
$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[ref]
both in the function definition and function call.value
to the reference variableAlso refer to the almost identical prior question here: Powershell passing argument values to parameters and back
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With