This is a duplicate of How to exit from ForEach-Object in PowerShell - I'm not sure how to mark that, but I'm asking the question again because there is a ton of helpful information in the answers to that question including ways to handle it. However, the accepted answer from 2012 doesn't seem correct and the nuggets of wisdom are buried and shouldn't be.
So my script is looping through all of the CSV files in a directory and then taking action on those that contain records with the wrong number of columns. When I first ran this, it took a long time and I realized that some of the CSVs actually have the correct number of columns for all rows and I didn't need to take action on them, so I decided to try and implement something to check for at least one row with the incorrect number of columns and then take some kind of action on the file. To do so, I needed to kick out of my ForEach-Object loop once I found a qualifying row.
Here is the original script:
$ParentPath = "C:\Users\<username>\Documents\Temporary\*"
$Files = Get-ChildItem -Path $ParentPath -Include *.csv
foreach ($File in $Files) {
$OldPath = $File | % { $_.FullName }
$OldContent = Get-Content $OldPath
$NewContent = $OldContent |
Where-Object {$_.split(",").Count -eq 11}
Set-Content -Path "$(Split-Path $OldPath)\$($File.BaseName).txt" -Value $NewContent
}
Implementing some type of 'pre-check' on the files proved difficult, even though I was able to use an answer from SO to properly write-out the 'bad lines' - I was unable to quit out of the ForEach-Object loop without processing all rows (thereby defeating the entire purpose of pre-checking the files for offending rows).
Code below works great at identifying the first bad row, and if you remove the ;break
then it'll write out every offending row:
Get-Content $OldPath | ?{$_} | %{if(!($_.split(",").Count -eq 11)){"Process stopped at line number $($_.ReadCount), incorrect column count of: $($_.split(",").Count).";break}}
So how do I combine the two scripts to pre-check files for an offending row, and then take action on the files that need it? See proposed answer below!