Move Files Containing X in their Names to Folder X

Viewed 105

I'm Trying to move files containing "Sxx" in their names to folder named "Sxx".

for example:

file1: S01E12.srt ----> /S01/S01E12.srt

file2: S03E14.jpg ----> /S03/S03E14.jpg

etc.

So i came up with these codes for creating folders using files having "Sxx" in their names and then moving them into the right folders.

For creating folders:

foreach ($name in (Get-ChildItem -File | % {$_.BaseName -replace 'E\d{2}',''}))
  {
   if ($name -like 'S*') {
       New-Item -path "$name" -ItemType Directory
       }
  }

For moving files:

get-childitem -File | where {$_ -like "S01*"} | move-Item -Destination "S01*"
get-childitem -File | where {$_ -like "S02*"} | move-Item -Destination "S02*"
...

etc.

Any idea how to replace hardcoding method for moving part?

If you have any advice or better code for any part that would be awesome too.

1 Answers

Below is my code. I created two foreach loops to go once through all files and afterwards through all folders. I used a substring to get part of the file names.

$files = Get-ChildItem -File -Path C:\users\Lenovo\Desktop\Test
$dir = Get-ChildItem -Path C:\users\lenovo\Desktop\Test -Directory
foreach ($item in $files) {
    foreach ($folder in $dir)
    {
        if (($item.Name).Substring(0,3) -like $folder.Name)
        {
            Move-Item -Path $item.FullName -Destination $folder.FullName
        }
    }
}

I create four files with S01.txt to S04.txt and it was working. To test whether your variable is empty, either you can write the variable with Write-Host or slightly more advanced, you can use the debug mode to see exactly what your variables contain.

Related