2

There are multiple arrays, and their contents might or might not be empty. If any of these arrays are empty, I would like to add a default value to them.

I have tried wrapping all the arrays into a container array and using Foreach-Object, but the default value does not appear to be assigned.

#... 

$arr1 = @()
$arr2 = @("a","b")
$arr3 = @("c","d")

@($arr1, $arr2, $arr3 | ForEach-Object {
    if($_.Count -le 0) {
        $_ = @("EMPTY")
    }
})

Write-Output $arr1

# ...

The empty array was not assigned

PS> $arr1
PS> <# NOTHING #>

Is it possible to set a default value for those arrays?

1 Answer 1

3

You're trying to modify variables, not their values. Therefore, you must enumerate variable objects, which you can obtain with Get-Variable:

$arr1 = @()
$arr2 = @("a","b")
$arr3 = @("c","d")

Get-Variable arr* | ForEach-Object {
  if ($_.Value.Count -eq 0) {
    $_.Value = @("EMPTY")
  }
}

$arr1 # -> @('EMPTY')

Alternatively, consider maintaining your arrays in a single hashtable rather than in individual variables:

$arrays = [ordered] @{
  arr1 = @()
  arr2 = @("a","b")
  arr3 = @("c","d")
}

foreach ($key in @($arrays.Keys)) {
  if ($arrays.$key.Count -eq 0) {
    $arrays.$key = @('EMPTY')
  }
}

$arrays.arr1 # -> @('EMPTY')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, @mklement0, for this detailed reply. Because my array names aren't consistent with a naming convention, I've used the second method of maintaining the arrays in a hashtable, which works just fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.