Search code examples
powershellglob

Powershell script to locate only files starting with specified letters and ending with .csv


cd 'A:\P\E\D'
$files = Get-ChildItem . *.CSV -rec

ForEach ($file in $files) {
    (Get-Content $file -Raw) | ForEach-Object { 
      *some simple code*
    } | Set-Content $file
    }

How to modify this powershell script to locate only files starting with letters A/a to O/o and ending with .csv in specified directory cd?

I thought the solution below would work, but the test file M_K_O_X.CSV stored in the cd directory was not found and modified. The solution above will find and modify the file. It's possible that I have the regex expression wrong or the problem is somewhere else? I tried also this regex -- "[A-O]..CSV"

cd 'A:\P\E\D'
$files = Get-ChildItem . -rec | Where-Object { $_.Name -like "[a-oA-O]*.*.CSV" }

ForEach ($file in $files) {
    (Get-Content $file -Raw) | ForEach-Object { 
      *some simple code*
    } | Set-Content $file
    }

Solution

  • Looking at your wildcard pattern, seems like you have an extra *. that shouldn't be there:

    'M_K_O_X.CSV' -like '[a-oA-O]*.*.CSV' # False
    'M_K_O_X.CSV' -like '[a-oA-O]*.CSV'   # True
    

    In this case you could simply use the -Include Parameter which supports character ranges. Also PowerShell is case insensitive by default, [a-oA-O]*.CSV can be reduced to [a-o]*.CSV:

    Get-ChildItem 'A:\P\E\D' -Recurse -Include '[a-o]*.csv' | ForEach-Object {
        ($_ | Get-Content -Raw) | ForEach-Object { 
            # *some simple code*
        } | Set-Content -LiteralPath $_.FullName
    }