Reputation: 111
All files in a folder have an _
(underscore) in the file name. All files should be moved into subfolders, were the subfolder name is the portion of the file name before the underscore. If the subfolder doesn't exist, it should be created.
Examples:
abc_123 -> moved to folder 'abc'
def_123 -> moved to folder 'def'
def_456 -> moved to folder 'def'
g_11 -> moved to folder 'g'
Obviously this will use Move-Item
but other than that I have no clue. Any help please?
Upvotes: -1
Views: 223
Reputation: 331
Get-ChildItem
to get all items from the root source directoryForEach-Object
to iterate through the resultsBaseName
property on each object/item will give you the file
name without the path or file extension interfering; then you can
use Split()
to obtain the part before the underscoreTest-Path
to check if the destination directory already existsMove-Item
to move the file from the source to the destinationNew-Item
with the
-ItemType "directory"
parameter to create it, then run Move-Item
[string]$rootSrc = "root-source"
[string]$rootDst = "root-destination"
Get-ChildItem -Path $rootSrc | ForEach-Object {
[string]$leafDst = $_.BaseName.Split("_")[0]
[string]$dst = "$rootDst\$leafDst"
if (Test-Path -Path $dst) {
Move-Item -Path $_.FullName -Destination $dst -Force
}
else {
New-Item -Path $rootDst -Name $leafDst -ItemType "directory"
Move-Item -Path $_.FullName -Destination $dst -Force
}
}
Upvotes: 1