Home > front end >  Incorporating Regex in Get-ChildItem
Incorporating Regex in Get-ChildItem

Time:01-14

I want powershell to return files from a folder whose file name starts with America and has csv extension. The folder contains files for different countries with csv, excel and txt formats.

The following command returns the files that are .csv but how can I also incorporate start with filtering to the below to get only America items?

Get-ChildItem ("C:\Users\Documents\Sales") -Filter *.csv

enter image description here

CodePudding user response:

The -Filter cannot use regex, but it does support the use of the * wildcard.

As RetiredGeek already commented, the easiest way to get the files that start with America and have the .csv extension is to use

Get-ChildItem -Path 'C:\Users\Documents\Sales' -File -Filter 'America*.csv'

the switch -File will make sure you only recieve files, not folders as well

If you do need to filter using regex, you can only do that by piping the results through to a Where-Object clause.
Suppose you want all files starting with 'America' or 'Mexico' and do not want files 'Canada' or any other country in your results. Then you could do

Get-ChildItem -Path 'C:\Users\Documents\Sales' -File -Filter '*.csv' |  # first return ony .csv files
Where-Object { $_.Name -match '^(America|Mexico)' }                     # then filter out all that do not start with America or Mexico

Regex details:

^                # Assert position at the beginning of the string
(                # Match the regex below and capture its match into backreference number 1
                 # Match this alternative (attempting the next alternative only if this one fails)
      America    # Match the character string “America” literally (case insensitive)
   |
                 # Or match this alternative (the entire group fails if this one fails to match)
      Mexico     # Match the character string “Mexico” literally (case insensitive)
)
  • Related