2012-06-13 53 views
2

我们有一个每天运行的脚本,用于从人们用来传输数据的区域中删除旧文件和目录。除了一小段,一切都很好。我想删除一个文件夹,如果它超过7天,它是空的。由于thumbs.db文件,脚本始终在文件夹中显示1个文件。我想我可以检查一下是否有一个文件是thumb.db,如果是这样,只需删除文件夹,但我确定有更好的方法。Powershell getfiles.count()排除thumbs.db


$location = Get-ChildItem \\dropzone -exclude thumbs.db 
foreach ($item in $location) { 

    other stuff here going deeper into the tree... 

    if(($item.GetFiles().Count -eq 0) -and ($item.GetDirectories().Count -eq 0)) { 

    This is where I delete the folder but because the folder always has 
    the Thumbs.db system file we never get here 

    } 

} 

 

回答

3
$NumberOfFiles = (gci -Force $dir | ?{$_ -notmatch "thumbs.db"}).count 
+0

好了,用这个答案的解决方案是这样的: 如果(?GCI $ item.FullName | {$ _ -notmatch '的Thumbs.db'})计数-le 0){ 删除文件夹... } – murisonc

+0

@murisonc我假设没有第二个'(''后'if('是在你的评论中的疏忽,并在你的代码是正确的,但我会建议包括'-Force'参数,因为我已经包括在我的回答,因为没有它'gci'不会找到隐藏的文件/文件夹''gci -Force'的功能类似于'ls -A' – SpellingD

+0

你在这两个部分都是正确的,但是我故意忽略了-Force,因为这是一个公共共享为人们交换数据和任何超过7天的旧被删除的脚本,如果任何人试图绕过它隐藏的文件夹它仍然被删除。但这让我想,因为gci没有得到隐藏的文件我可以使用if((gci $ item.FullName).count -le 0){Delete folder ...}。这是否正确,因为Thumbs.db文件是隐藏的系统文件? – murisonc

1

你可以尝试所有的文件/在你的目录的项目将被计入除了那些用分贝结束 的get-childitem -exclude选项:

$location = get-childitem -exclude *.db 

它也可以,如果你指定该文件排除,在这种情况下thumbs.db

$location = get-childitem -exclude thumb.db 

让我知道这是否工作。


啊,我也只是发现了一些,

$location = get-childitem -exclude *.db 

将只处理.db的项目的位置目录,如果你从你的GetFiles深入到树(比如()和GetDirectories()方法),那么你仍然可以找到一个thumb.db。因此,您必须在这些方法中添加exclude选项才能忽略thumbs.db。

因此,例如在您的$ item.getFiles()方法中,如果使用get-childitem,则还必须指定-exclude选项。

对不起,我应该仔细阅读你的问题。

+0

增加你的建议的代码,它仍然没有按”工作。 $ item.GetFiles()。Count行仍然返回1,并且我验证文件夹中唯一的文件是Thumbs.db。 – murisonc

+0

文件名可能区分大小写,是thumbs.db还是thumb.db(Captial T)? –

+0

我想到了,所以我尝试了Thumbs.db和thumbs.db。 – murisonc

1

使用此方法,以提供一个简单的文本文件的形式排除列表从您的计数排除特定文件或扩展:

$dir = 'C:\YourDirectory' 
#Type one filename.ext or *.ext per line in this txt file 
$exclude = Get-Content "C:\Somefolder\exclude.txt" 
$count = (dir $dir -Exclude $exclude).count 
$count