I have a folder containing video files. I need to create a folder for each file, where the folder name is the same as the file (minus file extension) and move that specific file into it's associated folder.
The end result should eliminate all files in the root, and each folder should contain a single file.
Example folder should start out looking like this:
c:\videos\video1.avi
c:\videos\video2.mov
c:\videos\video3.mkv
And then look like this:
c:\videos\video1\video1.avi
c:\videos\video2\video2.mov
c:\videos\video3\video3.mkv
Everything works except the last step of moving the files into their associated folders.
In this 2nd ForEach
I try to specify the destination path using the $basename
variable used in the first loop. This doesn't work as it results in moving all the files into a single folder, which is the last object passed to the $basename
variable from the 1st Foreach loop.
foreach ($filename in $VideoFiles) {
Move-Item -Path \\server1\Video\Staging\$filename -Destination \\server1\Video\Staging\$basename -verbose
}
This kind of makes sense but with my limited knowledge and experience I can't figure out another way to accomplish my goal. I started to look into nesting ForEach loops but I am guessing there is an easier way to accomplish this.
I tried the following command in the 2nd loop
Move-Item -Path \\server1\Video\Staging\$filename -Destination \\server1\Video\Staging\$filename -verbose
But of course, that variable is storing the file name (including extension) and did not move any files.
Any help will be greatly appreciated..!
Get-ChildItem -Path \\server1\video\staging | ForEach-Object {$_.basename} | Out-File \\server1\video\videonames.txt
$VideoNames = Get-Content \\server1\video\videonames.txt
Get-ChildItem -Path \\server1\video\staging | ForEach-Object {$_.name} | Out-File \\server1\video\videosfiles.txt
$VideoFiles = Get-Content \\server1\video\videosfiles.txt
foreach ($BaseName in $VideoNames) {
New-Item -ItemType Directory -Path \\server1\Video\Staging\$BaseName
}
foreach ($filename in $VideoFiles) {
Move-Item -Path \\server1\Video\Staging\$filename -Destination \\server1\Video\Staging\$basename -verbose
}
for /f
loop could do just exactly what you're asking. Even with PS, you've overcomplicated things - just create the folder and move the file, then move to the next folder and file. You don't need multiple loops.