Reputation: 37
I am trying to build a PowerShell script that can search for files with similar names inside of a folder.
The files will always have a similar name template:
filename(C).TIF
filename(M).TIF
filename(Y).TIF
filename(K).TIF
All I need to do is to extract the "filename", check if there are 4 similar ones (C,M,Y,K) and use it as a variable to move those files.
$files = Get-ChildItem -Path "E:\test" -Filter "*.TIF" |
Foreach-Object {$_.BaseName} | Sort-Object -Unique
$files = $files -replace ".{3}$"
$names = (Get-Unique -InputObject $files)
$names
The result looks like this:
jobname
jobname
jobname
jobname
test
test
test
test
But I need to sort by unique and count them, maybe, before action.
Upvotes: 1
Views: 1320
Reputation: 174435
But I need to sort by unique and count them, maybe, before action.
You definitely want the Group-Object
cmdlet!
As the name suggests, it... groups objects, based on some common property:
$filesByCommonBaseName = Get-ChildItem -Path "E:\test" -Filter "*.TIF" |Group-Object { $_.BaseName -replace '.{3}$' }
Now that you have them grouped correctly, you can start operating on them as such:
foreach($entry in $filesByCommonBaseName){
Write-Host "Operating on files starting with $($entry.Name)"
if($entry.Count -eq 4){
# we found four matches, move them!
$entry.Group |Move-Item -Destination $destinationDir -Force
}
}
Upvotes: 3