rocketsocks
rocketsocks

Reputation: 111

Need help creating script to move files to specific folders

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

Answers (1)

D-squared
D-squared

Reputation: 331

  • Use Get-ChildItem to get all items from the root source directory
  • Use ForEach-Object to iterate through the results
  • The BaseName 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 underscore
  • Use Test-Path to check if the destination directory already exists
  • Use Move-Item to move the file from the source to the destination
  • If the destination directory does not exist, use New-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

Related Questions