PowerShell比较了篇幅并删除文件/s



我真的想"结束"此脚本。我已经创建了一个小脚本,但是有一个IM只能从我输入的第一个字典中删除文件。

脚本shoud比较两个文件夹,如果我想删除它的旧版本或更新的文件,我想选择的文件。

//编辑

$path1 = Read-Host "Name the 1st Path"
$path2 = Read-Host "Name the 2nd Path"
$Folder1 = Get-ChildItem -Path $pfad1 -Recurse 
$Folder2 = Get-ChildItem -Path $pfad2 -Recurse
Write-Host "####################################"
Write-Host ( Get-ChildItem $pfad1,$pfad2 ).count
Write-Host "Files are in the folder"
Write-Host "####################################"
$frage = Read-Host "Are you sure you want to delete the files YES / NO ?"

if ($frage -eq $NO) { "Files stay " ; exit }
else {
        Compare-Object -ReferenceObject $Folder1 -DifferenceObject $Folder2 
 -IncludeEqual |
            Where-Object {$_.SideIndicator -eq "=="} | 
            ForEach-Object { 
            Remove-Item $_.InputObject.FullName | where { $_.lastwritetime -lt $altdate  } 
            }
                }

取决于文件夹的大小,这可能不是执行此操作的最佳方法。但这确实有效。

$files = $folder1 + $folder2
$files | 
    Group-Object name | 
    Foreach-Object {
        $_.Group | 
        Sort-Object LastWriteTime | 
        Select-Object -Last 1 
    } | 
    Remove-Item -Force

好的。iv'e重新设计了我最初的答案,以解决其一些简短的启动。此答案使您能够使用测试代码查看将删除和保留的内容。我知道我可以使用适当的详细开关和Whatif功能,但这似乎更容易。IVE解决了订购问题以及将删除非重复项目的问题。

$folder1 = 'c:tempreports1' 
$folder2 = 'c:tempreports2'

function Get-FilesForDeletion ($folder1, $folder2, [switch] $verbose){
    $files1 = Get-ChildItem $folder1
    $files2 = Get-ChildItem $folder2
    $files = $files1 + $files2
    $i = ($files | Select-Object -ExpandProperty Directory | Measure-Object -Maximum -Property Length).Maximum
    $files | 
        Group-Object name | 
        Where-Object Count -gt 1 |
        Foreach-Object {    
            $process = $_
            $deleteMe = $process.Group | 
                    Sort-Object LastWriteTime -Descending | 
                    Select-Object -Last 1 
            if($verbose){
                Write-Host "Processing $($process.Group.Name)..."
                $keepThese = $process.Group | 
                    Sort-Object LastWriteTime | 
                    Select-Object -Skip 1 
                Write-Host "  - Delete  $(($deleteMe.Directory.FullName).PadRight($i)) - LastWriteTime $($deleteMe.lastWriteTime) "
                $keepThese | ForEach-Object {
                    Write-Host "  - Keep    $(($_.Directory.FullName).PadRight($i)) - LastWriteTime $($_.lastWriteTime) "
                }              
                write-host " "
                write-host " "
            }
            $deleteMe
        } 
}
# testing code
#Get-FilesForDeletion -folder1 $folder1 -folder2 $folder2 -verbose | Out-Null
Get-FilesForDeletion -folder1 $folder1 -folder2 $folder2 -verbose | Remove-Item

相关内容

  • 没有找到相关文章

最新更新