Powershell: move files recursively

I am trying to copy all output files and assembly folders to the Bin folder ( OutputDir / Bin ), with the exception of some files that remain in 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 

Goal:

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

My first attempt:

 $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 cannot overwrite folders.

My second attempt:

 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 an alternative way to move files recursively in a simpler way using PowerShell?

+6
source share
2 answers

You can replace the Move-Item command with the Copy-Item command, after which you can delete the files that you moved by simply typing 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 
+6
source

As already mentioned, Move-Item will not overwrite folders, so you are left with copying. An alternative solution would be to call Robocopy for each file in each for-each loop using the / MOV switch (among others!); it moves and then deletes the original file.

0
source

Source: https://habr.com/ru/post/908443/


All Articles