2012-10-22 151 views
-1

到位,通過我們的開發人員之一引起的附加到電子郵件的文件在被複制到我們的服務器一遍又一遍的系統文件。PowerShell腳本刪除未參考文件

它附加一個唯一的GUID的文件名的前面,已經造成大約35,000重複使用不同的GUID。

我擁有所有我們要保留的文件列表,而是需要一個腳本引用此文件,並刪除不在此引用文件中的所有文件。

任何人都可以幫忙嗎?

+0

是否要繼續使用與GUID的附加文件名,或原始文件名(即不與GUID附加)文件名列表。 – David

回答

0

有一些細節,從你的描述丟失,所以這裏是我的假設:

追加的文件都遵循類似下面的表格:

62dc92e2-67b0-437e-ba06-bcbf922f48e8file14.txt 
66e7cbb3-873a-429b-b4c3-46597b5b5828file2.txt 
68c426a3-49b9-4a80-a3e8-ef73ac875791file13.txt 
etc. 

你要保留的文件列表看起來是像這樣:

file1.txt 
file12.txt 
file9.txt 
file5.txt 

代碼:

# list of files you want to keep 
$keep = get-content 'keep.txt' 

# directory containing files 
$guidfiles = get-childitem 'c:\some\directory' 

# loop through each filename from the target directory 
foreach($guidfile in $guidfiles) { 
    $foundit = 0; 

    # loop through each of the filenames that you want to keep 
    # and check for a match 
    foreach($keeper in $keep) { 
     if($guidfile -match "$keeper$") { 
      write-output "$guidfile matches $keeper" 

      # set flag that indicates we don't want to delete file 
      $foundit = 1 
      break 
     } 
    } 

    # if flag was not set (i.e. no match to list of keepers) then 
    # delete it 
    if($foundit -eq 0) { 
     write-output "Deleting $guidfile" 

     # As a sanity test, I'd suggest you comment out the line below when 
     # you first run the script. The output to stdout will tell you which 
     # files would get deleted. Once you're satisfied that the output 
     # is correctly showing the files you want deleted, then you can 
     # uncomment the line and run it for real. 
     remove-item $guidfile.fullname 
    } 
} 

其他注意事項: 你提到這個 「造成了一些重複的35000」。這聽起來像是同一個文件可能已被複制多次。這意味着您可能還想刪除要保留的文件的重複項,以便只保留一個。我無法從描述中肯定地判斷這是否屬實,但腳本也可以修改以實現這一點。