Script to move files into upper level directory

Soldato
Joined
1 Nov 2002
Posts
6,487
Location
South Shields
My google skills are weak tonight.
Im after a script or method that would allow me to move a file from a directory into the upper level directory and then delete the empty folder.
Currently the structure is like this:
Code:
Folder0:
     Folder1:
          Folder:
               File.ext
     Folder2:
          Folder:
               File.ext
     Folder3:
          Folder:
               File.ext
Ideally i'd like the script to be ran from the very top level folder as it contains 1500 sub folders. The files inside each subfolder all have the same extension.
Below is the structure i'd like.
Code:
Folder0:
     Folder1:
               File.ext
     Folder2:
               File.ext
     Folder3:
               File.ext
I dont mind which type of script, powershell, vbscript, linux based etc
 
This might sound simple and it depends on what you're using, but in Windows 7 I find the easiest way to do this is to go to the parent folder that contains the child folders, in the top right I search for *.fileextension. Once it finds all the files, I just cut and paste them where I want them to go.

If this needs to be run on a schedule then you'll probably want a script to be run instead. I am best with PowerShell, so if you need one and don't mind it being written in PowerShell then I can probably help. Let me know.
 
...in Windows 7 I find the easiest way to do this is to go to the parent folder that contains the child folders, in the top right I search for *.fileextension. Once it finds all the files, I just cut and paste them where I want them to go.
This wont work as I don't want all of the files in the top level directory, they only need to be moved up a single level.

Its not a major problem if I cant move them, just a slight inconvenience.
Thanks anyway.
 
Sorry, I assumed you didn't know how to script it, powershell would be fine as the files are stored on a Server 2008 machine.
It also doesn't need to be run on a schedule its a one off task for now, although im likely to come across this problem again in the near future.
 
This should work, test it though as I can't take responsibility for any problems you have!

You will need to replace the directory and the file extension parameters to suit your needs. It will mess up if tries to write a duplicate file and give you an exception, this behaviour could be changed to do something else but that wasn't in the guidelines:

Code:
$Directory = "C:\tmp"
$Extension = ".txt"

$ChildItems = Get-ChildItem $Directory -recurse

foreach ($Child in $ChildItems)
{
	if ($Child.Extension -eq $Extension)
	{
		$ChildDirectory = $Child.DirectoryName
		$NewPath = $ChildDirectory.Substring(0, ($ChildDirectory.LastIndexOf("\"))) + "\" + $Child.Name
		
		Try
		{
			$Child.MoveTo($NewPath)
		}
		Catch [Exception]
		{
			Write-Host "$($_.exception)" -ForegroundColor Yellow
		}
	}
}
 
Back
Top Bottom