2017-09-29 117 views
-2

我真的想「結束」這個腳本。我已經創建了一個小腳本,但只有一個即時消息只能從我輸入的第一個字典中刪除這些文件。Powershell比較Lastwritedate並刪除文件

腳本應該比較兩個文件夾,並且如果存在具有相同名稱的文件,我想選擇是否刪除舊版本或新版本。

//編輯

$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 } 
      } 
       } 
+0

請添加您到目前爲止嘗試過的內容,並將您的問題限制爲特定問題。 SO不是編寫代碼的頁面 –

+0

完成,ty爲信息 – BGL

回答

0

根據您的文件夾的大小,這可能不是這樣做的最高效的方式。但它確實有效。

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

好的。 Iv'e重做了我原來的回答,以解決它的一些缺點。這個答案使您能夠使用測試代碼查看將被刪除和保留的內容。我知道我可以使用一個適當的詳細開關和whatif功能,但這似乎更容易。我解決了訂購問題和非重複項目將被刪除的問題。

$folder1 = 'c:\temp\reports1' 
$folder2 = 'c:\temp\reports2' 


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 
+0

非常感謝,它的工作原理! – BGL

+0

您可以將其標記爲已回答 – Steve

+0

我第一次嘗試,它工作。現在它不再工作了。它只會刪除最新的文件,並且不會比較文件名... – BGL