'Powershell: create directory using filenames without extension and move files to new directory
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
#}
Solution 1:[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
}
Solution 2:[2]
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
}
Solution 3:[3]
I gave up on powershell and used file2foldergui instead
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Roshan |
| Solution 3 | David Johnson |
