Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Move Files recursively

I am trying to copy all build output files and folders into a Bin folder (OutputDir/Bin) except of some files which stay in the OutputDir. The Bin folder will never be deleted.

Initial condition:

Output
   config.log4net
   file1.txt
   file2.txt
   file3.dll
   ProjectXXX.exe
   en
      foo.txt
   fr
      foo.txt
   de
      foo.txt

Target:

Output
   Bin
      file1.txt
      file2.txt
      file3.dll
      en
         foo.txt
      fr
         foo.txt
      de
         foo.txt
   config.log4net
   ProjectXXX.exe

My first try:

$binaries = $args[0]
$binFolderName = "bin"
$binFolderPath = Join-Path $binaries $binFolderName

New-Item $binFolderPath -ItemType Directory

Get-Childitem -Path $binaries | ? {$_.Name -notlike "ProjectXXX.*" -and $_.Name -ne "config.log4net" -and $_.Name -ne $binFolderName }  | Move-Item -Destination $binFolderPath

This does not work, because Move-Item is not able to overwrite folders.

My second try:

function MoveItemsInDirectory {
    param([Parameter(Mandatory=$true, Position=0)][System.String]$SourceDirectoryPath,
          [Parameter(Mandatory=$true, Position=1)][System.String]$DestinationDirectoryPath,
          [Parameter(Mandatory=$false, Position=2)][System.Array]$ExcludeFiles)
    Get-ChildItem -Path $SourceDirectoryPath -Exclude $ExcludeFiles | %{
        if ($_ -is [System.IO.FileInfo]) {
            $newFilePath = Join-Path $DestinationDirectoryPath $_.Name
            xcopy $_.FullName $newFilePath /Y
            Remove-Item $_ -Force -Confirm:$false
        }
        else
        {
            $folderName = $_.Name
            $folderPath = Join-Path $DestinationDirectoryPath $folderName

            MoveItemsInDirectory -SourceDirectoryPath $_.FullName -DestinationDirectoryPath $folderPath -ExcludeFiles $ExcludeFiles
            Remove-Item $_ -Force -Confirm:$false
        }
    }
}

$binaries = $args[0]
$binFolderName = "bin"
$binFolderPath = Join-Path $binaries $binFolderName
$excludeFiles = @("ProjectXXX.*", "config.log4net", $binFolderName)

MoveItemsInDirectory $binaries $binFolderPath $excludeFiles

Is there any alternative way of moving files recursively in a more easy way using PowerShell?

like image 306
Rookian Avatar asked Feb 14 '12 15:02

Rookian


1 Answers

You could replace the Move-Item command with an Copy-Item command and after that, you can delete the files you moved by simply calling Remove-Item:

$a = ls | ? {$_.Name -notlike "ProjectXXX.*" -and $_.Name -ne "config.log4net" -and $_.Name -ne $binFolderName }
$a | cp -Recurse -Destination bin -Force
rm $a -r -force -Confirm:$false
like image 165
tklepzig Avatar answered Nov 11 '22 00:11

tklepzig