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

Time:01-24

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
    }

CodePudding user response:

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
}

CodePudding user response:

As commented, I would use the standard wildcard -Filter to filter for all files with a .csv extension.
Then pipe to a Where-Object clause in which you can use regex -match

$files = Get-ChildItem -Path 'A:\P\E\D' -Filter '*.csv' -File -Recurse | 
         Where-Object { $_.Name -match '^[a-o]' }

foreach ($file in $files) {
    # switch `-Raw` makes Get-Content return a single multiline string, so no need for a loop
    $content = Get-Content -Path $file.FullName -Raw 
      # *some simple code manipulating $content*
    $content | Set-Content -Path $file.FullName
}

However, if these are valid csv files, I would not recommend using a pure textual manipulation on them, instead use Import-Csv -Path $file.FullName and work on the properties on each of the objects returned.

  • Related