1

I don't understand why I get the correct count of my array when using ForEach, but not when I pipe to ForEach-Object. The piped count is always 0.

Correct Count:

$hash = @(Get-ChildItem C:\Dir -Recurse -Include *.txt | Where {$_.length -gt 0})
ForEach ($i in @hash) {
     Write-Host = $i.BaseName
}
"Array Count = $($hash.Count)"

Output:

File1.txt
File2.txt
Array Count = 2

Incorrect Count:

$hash = @(Get-ChildItem C:\Dir -Recurse -Include *.txt | Where {$_.length -gt 0}) | ForEach-Object {
    Write-Host $_.BaseName
}
"Array Count = $($hash.Count)"

Output:

File1.txt
File2.txt
Array Count = 0

2 Answers 2

0

In your second formulation the ForEach-Object is eating up the values found by Get-ChildItem and returning nothing useful to $hash.

You should enclose the entire assignment to $hash in the parenthesis to have it evaluated before it is grabbed by ForEach-Object.

This is the formulation that worked for me in my test:

($hash=@(Get-ChildItem -Path "C:\Temp\*" -Include "*.jpg") | Where {$_.length -gt 0}) | ForEach-Object { Write-Host $_.BaseName }
3
  • that works great. Thanks for the great explanation.
    – ToToRoYN
    Commented Jul 5, 2019 at 19:09
  • My next questions is how to display the current index being processed. I'm wanting to write to a log something like 1 of 4, 2 of 4, etc
    – ToToRoYN
    Commented Jul 5, 2019 at 19:23
  • That would need to be asked in another post.
    – harrymc
    Commented Jul 5, 2019 at 19:25
0

$hash is null in the second example (type $hash -eq $null to verify). The output of the pipeline is "consumed" by the Write-host in your loop --- there's nothing left to assign to $hash. If you want the names assigned to $hasn and displayed on the console, something like this would work:

$hash = @(Get-ChildItem c:\dir -Recurse -Include *.txt | Where {$_.length -gt 0}) | ForEach-Object {
    $_.BaseName # continues through pipeline to populate $hash
    write-host $_.basename
} 
"Array Count = $($hash.Count)"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .