Bharat Patel
Bharat Patel

Reputation: 21

PowerShell: How to increment counter when condition is satisfied

My requirement is to go through each directory and sub-directory and find a character after the third dash(-) in a file name and if it is an "A", increment the counter and at the end of the process, write to the host total number of files that met the required condition. How would I do that?

Here is my script:

$counter = 0
dir .\ -Recurse | % {
    if (($_.Name.Split("-")[3] -notmatch "[^C]")) {
        $counter++
        write-Host $_.Name.Split("-")[3]
        $counter
    }
}

Upvotes: 0

Views: 45101

Answers (1)

Joey
Joey

Reputation: 354356

If you want to print the counter only once, move it out of the ForEach-Object:

$counter = 0
dir .\ -Recurse | %{
  if (($_.Name.Split("-")[3] -notmatch "[^C]")) {
    $counter++
    write-Host $_.Name.Split("-")[3]
  }
}
$counter

However, I'd propose to not go that route at all. That code is not very nice to read as there's rarely a reason to implement a counter that way (outside maybe of code-golfing).

An easier way is to use the pipeline to get all files matching your condition and then get their count:

(Get-ChildItem -Recurse |
  Where-Object { $_.Name.Split('-')[0] -match 'A' }).Count

If there are a lot of files and memory consumption is an issue, you can use the pipeline to pipe the result to Measure-Object:

(Get-ChildItem -Recurse |
  Where-Object { $_.Name.Split('-')[0] -match 'A' } |
  Measure-Object).Count

Upvotes: 2

Related Questions