How can I move files up two directory levels in PowerShell?

0
21
Asked By CuriousCoder123 On

I'm dealing with a bunch of subdirectories that are nested deeper than I intended. For instance, I have files located at paths like this:

C:abcxabcxfoo.bar
C:abcyabcybar.foo
C:abczabczfoobar.barfoo

What I need is to move them up two levels, so everything from the above paths should instead be found under:

C:abcxfoo.bar
C:abcybar.foo

Unfortunately, a script I tried failed, and I'd rather not wait days to rerun it or figure out Ruby now. Does anyone know how to do this effectively in PowerShell?

4 Answers

Answered By DataDude88 On

Just remember, you can refer to parent directories using `..` - so to move files up two levels, you’ll actually go to `....`. Test it with a couple of files to ensure you're getting the slashes right before doing a bulk move!

Answered By TechWhiz007 On

If you're always dealing with a specific number of parent directories, you could use PowerShell for this. Here's a potential script:

```powershell
$RootDirectory = 'c:abc'
$FileArray = Get-ChildItem -File -Recurse -Path $RootDirectory
foreach ($file in $FileArray) {
$DestinationDirectory = $file.Directory.Parent.Parent.FullName
Move-Item -Path $file.FullName -Destination $DestinationDirectory -WhatIf
}
```
Check the paths first, and just remove `-WhatIf` once you're sure it looks good!

Answered By CodeNinja On

You'll want to set up your paths in variables and use the `Copy-Item` cmdlet to get this done. Here's a basic pattern:

```powershell
$currentpath = "C:abcxabcx*"
$targetpath = "C:abcx"
Copy-Item -Path $currentpath -Destination $targetpath -Recurse
```
After this, you can use a loop for your other directories. Don't forget to check the docs for more info on commands!

Answered By FileMoverPro On

You'll basically want to strip off two parent folders from each file path before moving. Here’s a simple outline:

```powershell
$Root = 'C:abc'
Get-ChildItem -Path $Root -File -Recurse | ForEach-Object {
$target = $_.Directory.Parent.Parent.FullName
Move-Item $_.FullName -Destination $target -WhatIf
}
```
This way, you're moving everything into the right place. Just get rid of `-WhatIf` after verifying everything looks okay. If you want to move folders too, adjust the parameters accordingly!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.