Powershell:以递归方式移动文件 [英] Powershell: Move Files recursively
问题描述
我试图将所有生成的输出文件和文件夹复制到 Bin 文件夹( OutputDir/Bin )中,除了一些保留在 OutputDir . Bin 文件夹将永远不会被删除.
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.
初始条件:
Output
config.log4net
file1.txt
file2.txt
file3.dll
ProjectXXX.exe
en
foo.txt
fr
foo.txt
de
foo.txt
目标:
Output
Bin
file1.txt
file2.txt
file3.dll
en
foo.txt
fr
foo.txt
de
foo.txt
config.log4net
ProjectXXX.exe
我的第一次尝试:
$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
这不起作用,因为Move-Item
无法覆盖文件夹.
This does not work, because Move-Item
is not able to overwrite folders.
第二次尝试:
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
是否有其他替代方法可以使用PowerShell以更简单的方式递归移动文件?
Is there any alternative way of moving files recursively in a more easy way using PowerShell?
推荐答案
您可以将Move-Item
命令替换为Copy-Item
命令,然后,您可以通过简单地调用Remove-Item
来删除移动的文件:
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
这篇关于Powershell:以递归方式移动文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!