2012-10-22 106 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”。这听起来像是同一个文件可能已被复制多次。这意味着您可能还想删除要保留的文件的重复项,以便只保留一个。我无法从描述中肯定地判断这是否属实,但脚本也可以修改以实现这一点。