1

i´m a beginner in Powershell, i have some scripts working. but now I´m stucked with this little problem. I have this little script. I have a folder with some files $ORIGEN. I need to get all those name files that match with te values in the variable $ARCHIVOS, and put them in a new variable $DATA. Can anyone tell me how i can make a match between the names in $ARCHIVOS with the files in the folder?. If i use only 1 value in the variable $ARCHIVOS, it works fine, but when i have an array y doesn´t match with anything. I tried many solutions, but nothing. THanks in advance for some help. And sorry by my english

$ORIGEN= "C:\FILES\"
$ARCHIVOS='MLR*.384', 'MP0*.384'

 $data= Get-ChildItem $ORIGEN | Where-Object{$_.Name -match $ARCHIVOS}
 Write-Host $data
Markkus
  • 13
  • 3

1 Answers1

2

Combine Get-ChildItem (or, since you're not recursing, just Get-Item) with * and -Include, which (unlike -Filter) accepts an array of wildcard patterns:[1]

Get-ChildItem -File $ORIGEN/* -Include $ARCHIVOS
  • -File instructs Get-ChildItem to return matching files only (rather than also directories).

  • The /* (\*) wildcard appended to the input path ($ORIGEN) is necessary, because _Include and -Exclude, in the absence of -Recurse, are only applied to the input path(s) themselves, not their child items.


If you want only the names of the matching files, simply access the .Name property on the output from the Get-ChildItem call via (...), the grouping operator, which, thanks to member-access enumeration, returns the matching files' names as an array (assuming there's at least two):

$fileNames = (Get-ChildItem -File $ORIGEN/* -Include $ARCHIVOS).Name

As for what you tried, $_.Name -match $ARCHIVOS:

  • The -match operator operates on regular expressions (regexes), not on wildcard expressions, yet your $ARCHIVOS array contains wildcard expressions.

  • Additionally, -match doesn't (meaningfully) accept an array of regexes on the RHS.

  • If you did want to solve this problem with -match (which isn't necessary, given the shorter and more efficient solution shown at the top), you'd have to create a single regex that uses alternation (|):

    # Note how the individual patterns are now expressed as *regexes*
    # and are *anchored* with ^ and $ to ensure that the *entire name* matches.
    # By default, -match finds *substrings*.
    $_.Name -match ('^MLR.*\.384$', '^MP0.*\.384$' -join '|')
    

[1] Additionally, -Filter - which with a single pattern is generally preferable to -Include for performance reasons - doesn't use PowerShell's wildcard language, but delegates matching to the host platform's file-system APIs. This means that range or character-set expressions such as [0-9] and [fg] are not supported, and, on Windows, several legacy quirks affect the matching behavior - see this answer for more information.

mklement0
  • 382,024
  • 64
  • 607
  • 775