0

I'm trying to move files (a bunch of files in a subdirectory), create a subfolder if it doesn't exist and then move the files to the subfolder

$files = Get-ChildItem -Path H:\Movies -File
#  for each($file in $files){
$file = $files[0]
$filename = [io.path]::GetFileNameWithoutExtension($file)
$path= "H:\movies\" + $filename
if (!(test-path -Path $path )){ #always returns false?
New-Item -ItemType Directory -Force -Path $path  
}
Move-Item $file.FullName $path
#}

3 Answers 3

1

I would try something like that:

$path = 'H:\Movies'
$files = Get-ChildItem -Path $path -File

foreach ($file in $files){
   # Get filename without extension
   $filename = $file.BaseName

   # Build new folderpath
   $newFolderPath = Join-Path -Path $path -ChildPath $filename

   # Check if folder already exists
   if (-not(Test-Path -Path $newFolderPath)) {
       New-Item -Path $path -Name $filename -ItemType Directory
   }

   # Move file to new folder
   $destination = Join-Path -Path $newFolderPath -ChildPath $file.Name
   Move-Item -Path $file.FullName -Destination $destination
}
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! You can omit Test-Path when using New-Item with parameter -Force. It creates new directory only if it doesn't already exists.
Just tried it, works! Thanks for the tip @zett42
0

I have Tested the below code using foreach and working fine for me.

$files = Get-ChildItem -Path E:\Test -File

foreach($file in $files){

 #Write-Output $file.Name
 $filename = [io.path]::GetFileNameWithoutExtension($file)
 Write-Output $filename
 $path= "E:\Test\" + $filename
 Write-Output $path
 if (!(test-path -Path $path )){ 
    Write-Output "Not Exists: $path"
    #New-Item -ItemType Directory -Force -Path $path 
    New-Item -ItemType Directory -Path $path
   }
 Move-Item $file.FullName $path

}

4 Comments

I hate it when it works for me solutions, yet doesn't work for ME. The directories are created but the files are not moved.
I have spaces in the filenames could this be the problem?
@DavidJohnson Working fine for me though spaces in the filename.
creates the directories fine.. just doesn't move the files.. I tried replacing the spaces with .'s and also on an exfat volume.. tried with windows server 2016 in a vm same old .. directories made files not moved
0

I gave up on powershell and used file2foldergui instead

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.