2
$variable = "test", "test1", "test2", "","test3"
Write-Host $variable
foreach($item in $variable)
{
if (-not $item -or $item -eq "") {
    $item ="N/A"
}
}
Write-Host $variable
  1. this is the OuptPut: test test1 test2 test3
  2. this is what I expect : test test1 test2 N/A test3
mklement0
  • 382,024
  • 64
  • 607
  • 775
ajra
  • 31
  • 4

2 Answers2

3

Strings in .NET are immutable and passed by value - and when you assign a new value to $item it won't affect the existing string value extracted from $variable array.

Use a for loop to write back to the array:

for($i = 0; $i -lt $variable.Count; $i++) {
    if ([string]::IsNullOrEmpty($variable[$i])) {
        $variable[$i] = "N/A"
    }
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
1

To complement Mathias helpful answer, which shows in-place modification of an array, with an alternative that creates a new array, taking advantage of the fact that you can use entire statements as expressions in PowerShell, with the results getting automatically collected in an array (if there are two or more output objects).

$variable = "test", "test1", "test2", "","test3"

# Note:
#  If you want to ensure that $variable remains an array even if the loop 
#  outputs just *one* string, use:
#     [array] $variable = ... 
$variable = 
  foreach ($item in $variable) { if (-not $item) { 'N/A' } else { $item } }

Note:

  • -not $item is sufficient to detect both an empty string an a $null value, based on PowerShell's automatic to-Boolean conversion rules, which are summarized in the bottom section of this answer.

  • While in-place updating is more memory-efficient, with smallish arrays creating a new one isn't a concern.

mklement0
  • 382,024
  • 64
  • 607
  • 775