Home > Mobile >  PowerShell: Iterate through all arrays and push a default value if empty
PowerShell: Iterate through all arrays and push a default value if empty

Time:06-30

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?

CodePudding user response:

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')
  • Related