Home > database >  How do I move files and folders to a parent folder in Power Shell?
How do I move files and folders to a parent folder in Power Shell?

Time:10-10

I got a list of directories like this:

root
|
 - dist
      | 
       _ fileA.js
       _ fileB.js
       _ folder1
              | 
               _ file1a.js
       _ folder2
              | 
               _ file2a.js
               _ folderb
                 | 
               _ file2ba.js

And I want to move the content of dist into the root folder, like this:

root
|
    _ fileA.js
    _ fileB.js
    _ folder1
           | 
            _ file1a.js
    _ folder2
           | 
            _ file2a.js
            _ folderb
               | 
                _ file2ba.js

I tried:

$logfiles = Get-ChildItem $(System.ArtifactsDirectory)/dist/custom -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.Name -like '**/*.*' } | Select-Object FullName
ForEach ($logfile in $logfiles.FullName) {Copy-Item $logfile -Destination "$(System.ArtifactsDirectory)"}

But it didn't work.

CodePudding user response:

In PowerShell prompt, go to dist folder, and run the following code:

$source = 'root\dist'
$destination = 'root\'

Get-ChildItem $source -Recurse | ForEach-Object {
    $newPath = $_.FullName -Replace [regex]::Escape($source), $destination
    Move-Item $_ -Destination $newPath -Force
}

The above code uses Get-ChildItem to recursively fetch all the files/folders from source folder, and then Move-Item puts each item in the destination folder in exactly the same hierarchy as it was in the source folder.

CodePudding user response:

Much quicker would be to use robocopy for this:

robocopy X:\root\dist X:\root /S /Move
  • Related