Home > Net >  Powershell: create directory using filenames without extension and move files to new directory
Powershell: create directory using filenames without extension and move files to new directory

Time:04-08

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
#}

CodePudding user response:

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
}

CodePudding user response:

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

}
  • Related