简体   繁体   中英

Powershell move all files and subfolders in a child folder to CURRENT directory

I tried this, no error but no files have modved:

Get-ChildItem -Path "subfolder\" -Recurse |  Move-Item -Destination "."

Update: I don't want ABSOLUTE but RELATIVE path

Your answer will be something like:

Move-Item -Path 'subfolder\*' -Destination . -Force

This is relative and will process all hidden files en folders as well.

Set-Location 'C:\Users\username\Desktop\newFolder';
Get-ChildItem -Path 'C:\Users\username\Desktop\oldFolder\*.txt' -Recurse -File | Move-Item -Destination $(get-location).Path;

This may seem like a crazy attempt and to be honest the question isn't as comprehensive as I'd like. For example: I'm not sure if the folder will only every be 1 level deep or could be further down from the current directory. At any rate, I got something that seems to be working basically by not bothering with recursion:

$SubFolder = 'YourFolderName'
$SubFolder = Get-Item .\$SubFolder

Get-ChildItem $SubFolder |
ForEach-Object{
    $Destination = $_.FullName -Replace "$($SubFolder.FullName.Replace('\','\\'))", ".\"
    $NewParent   = $Destination -Replace $_.Name 

    Move-Item $_.FullName -Destination $NewParent    
}

I think the trick here is you have to move to the parent's parent, etc or however many levels back/up. So figure out what the new parent should be using the current directory syntax .\ . Once you have that you can move everything from the first level over not using recursion. Move-Item on a folder it knows to move the whole thing, and the files that are found in Sub-folder itself will obviously move to the new correct parent.

I had another working version that did use recursion, but this seems more concise and much to my surprise this seems to work. However, I'm not thrilled with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM