Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you move files/folders across volumes with Powershell?

Tags:

powershell

I try to move a folder with PowerShell

move-item  c:\test c:\test2

works, but

move-item c:\test  \\192.168.1.50\c$\test2

does not and tells me

Move-Item : Source and destination path must have identical roots. Move will not work across volumes.

like image 714
Ilyax Avatar asked May 26 '11 12:05

Ilyax


2 Answers

If test is a directory, it won't work, as the documentation for Move-Item states:

Move-Item will move files between drives that are supported by the same provider, but it will move directories only within the same drive.

You can use Copy-Item followed by a Remove-Item in that case:

try {
  Copy-Item -Recurse C:\test \\192.168.1.50\c$\test2 -ErrorAction Stop
  Remove-Item -Recurse c:\test
} catch {}

Another option, if you don't rely on PSDrives, would be to simply use xcopy or robocopy.

like image 79
Joey Avatar answered Sep 19 '22 07:09

Joey


This needs to be tightened up and should probably be made into a function but it works.

$source = "<UNC Path>"
$destination = "<UNC Path>"

if (test-path $destination -PathType Container) 
{
  foreach ( $srcObj in (get-childitem $source )) 
  { 
    $srcObjPath = "$($srcObj.fullname)"
    $destObjPath = "$($destination)\$($srcObj.name)" 
    If((Test-Path -LiteralPath $destination)) 
     {
       copy-item $srcObjPath $destination -recurse
       if ( (Test-Path -Path $destObjPath ) -eq $true)
       {
        if ( (compare-object (gci $srcObjPath -recurse) (gci $destObjPath -recurse)) -eq $null)
        {
         write-output "Compare is good. Remove $($srcObjPath)"
         remove-item $srcObjPath -recurse
        }
        else
        {
          write-output "Compare is bad. Remove $($destObjPath)"
          remove-item $destObjPath -recurse
         }
       }
       else 
       { 
        write-output "$($destination) path is bad" 
       }
     }
  else
  {
    write-output "bad destinaton: $($destination)"
  }
 }
}
like image 29
brenbart Avatar answered Sep 19 '22 07:09

brenbart