Question:
I have a list of files say…
1 2 3 4 5 6 7 |
T123_Product_1.jpg T123_Product_2.jpg T123_Product_3.jpg T456_Product_1.jpg T456_Product_2.jpg T456_Product_3.jpg |
etc. etc. etc. for about 900 more files
What I am needing to do is create a folder based on the characters before the first underscore, but to not repeat it since there are multiple files.
So in the example above, I would only want two folders named T123 and T456.
Then I would need the script to place the appropriate files in the folder.
I had found some codes in this thread, but they don’t exactly do what I’m looking for.
1 2 3 4 5 6 7 8 9 10 |
$Files = Get-ChildItem -Path 'C:\Info\AUGUST 2011\Checklists\' -Filter 'DET1__*' $Files | ForEach-Object { $FileFullName = $_.FullName $TempFileName = "$($FileFullName).tmp" $DestinationFileName = "$FileFullName\$($_.Name)" Move-Item $FileFullName $TempFileName New-Item -Path $FileFullName -ItemType Directory Move-Item $TempFileName $DestinationFileName } |
Any help?
Answer:
The easiest way here would be to group the files by the first part, which will then become the directory name. In typical PowerShell pipeline manner this is fairly succinct:
1 2 3 4 5 6 7 8 9 |
Get-ChildItem -File | # Get files Group-Object { $_.Name -replace '_.*' } | # Group by part before first underscore ForEach-Object { # Create directory $dir = New-Item -Type Directory -Name $_.Name # Move files there $_.Group | Move-Item -Destination $dir } |