Home > other >  Variable scope within foreach-object in Powershell
Variable scope within foreach-object in Powershell

Time:10-13

I am trying to understand the output & error message for:

# declare empty array
$thisDataArray = @()
# assign array values
$thisDataArray = '123','cadabra','456','789','trouble'
# declare empty array to receive specific values
$letters = @()
# use this pattern to filter array members that contain letters
$regex = "[a-z]"

# confirm the array values
Write-Host $thisDataArray
# pipe array & filter to find the values
$thisDataArray | Select-String -AllMatches -Pattern $regex -CaseSensitive | ForEach-Object { $letters = $_.Matches.Value} 
# output the result
Write-Host $letters

The error is: The variable $letters is assigned but never used. And the output is:

123 cadabra 456 789 trouble
t r o u b l e

My questions are:

  1. How is Write-Host $letters not using the assigned variable $letters?
  2. Why do I only get the one array member 'trouble' from my $regex?
  3. And finally. Why are there spaces between the chars of trouble e.g 't r o u b l e'

Any suggestions appreciated.

CodePudding user response:

  1. How is Write-Host $letters not using the assigned variable $letters?

Because it is outside the ForEach-Object loop, hence, you're only reading the last result from that variable assignment. You probably wanted:

$thisDataArray | Select-String -AllMatches -Pattern $regex -CaseSensitive | ForEach-Object {
    $letters = $_.Matches.Value
    Write-Host $letters
}

Though, is worth noting that output to console is implicit unless captured or redirected, so, Write-Host might not be needed nor is a variable assignment:

$thisDataArray | Select-String -AllMatches -Pattern $regex -CaseSensitive | ForEach-Object {
    $_.Matches.Value
}
  1. Why do I only get the one array member 'trouble' from my $regex?

You don't, you would get cadabra and trouble assuming enter image description here

  • Related