Andrea Morresi
Andrea Morresi

Reputation: 41

POWERSHELL script to move only files with numeric digits (within the filename) in common

I was helped in the past few days to find a POWERSHELL script that would help me move only files that had the first 8 characters in common.

The script is the one below and it works perfectly

$destination_folder = "C:\TEMP\DESTINATION"
$filelist = Get-ChildItem -Path "C:\TEMP\ORIGIN" -File -Force -Recurse
$filelist|Group-Object -Property {$_.basename.Substring(0,8)}|Where-Object Count -gt 1 |
ForEach-Object {$_.Group  | Move-Item -Destination $destination_folder}

What I would like, and what would help me a lot, is to modify the above script in such a way that files that have at least 8 numeric characters in common are moved (even if they are not at the beginning of the name) so that the search is performed on the entire file name and not only on the first 8 characters.

Do you think it is possible to obtain such a result?

Thanks in advance to everyone

Upvotes: 1

Views: 419

Answers (1)

Lee_Dailey
Lee_Dailey

Reputation: 7489

since your specific Question is about getting the needed digits from a string, this is how how to do that one thing.

the code ...

[regex]::Match('asdf1234567890987654321asdf' -replace '\D', '^\d{8}').Value

output = 12345678

what the code does ...

  • [regex]::Match(
    uses the regex type accelerator to call the match static method of that type.
  • 'asdf1234567890987654321asdf' -replace '\D'
    this derives the string for the Match call to use. it strips out the non-digit chars by replacing them with nothing at all.
  • , '^\d{8}'
    this is the pattern for the Match call to use on the above string. it grabs the 1st 8 chars of the resulting replacement string.
    please note that this will cause your Group-Object call to work on a .BaseName that has more than 8 digits ... not just on those that have exactly 8 digits.
  • ).Value
    grabs the string in the .Value property of the object form the previous [regex]::Match() call

you will want to replace that silly example string with the .BaseName from your fileinfo object.

Upvotes: 1

Related Questions