powershell GCI以递归方式跳过文件夹和某些文件类型

时间:2013-01-18 18:49:12

标签: powershell directory file-extension get-childitem

目前我正在使用此行收集特定路径(及其后)的所有文件

$files = Get-ChildItem -Path $loc -Recurse | ? { !$_.PSIsContainer }

但是现在我一直要求生成这个列表,同时排除(例如)所有" docx"和" xlsx"文件...和名为"脚本的文件夹"和他们的内容

我想将这些文件扩展名和目录名从txt文件读入数组,然后只使用该数组。

速度也很重要,因为我将对这些文件执行的功能需要足够长的时间,我不需要这个过程减慢我的脚本10完全放松(有点可以)

非常感谢任何输入

失败的尝试:

gi -path H:\* -exclude $xfolders | gci -recurse -exclude $xfiles | where-object { -not $_.PSIsContainer }

我认为这样可行,但只在H:\ drive

的根目录下排除了文件夹

4 个答案:

答案 0 :(得分:3)

这样的东西?我只比较了相对路径(来自$ loc的路径),以防$loc包含一个要忽略的文件夹名称。

$loc = "C:\tools\scripts\myscripts\"
$files = Get-ChildItem -Path $loc -Recurse -Exclude *.docx, *.xlsx | ? { !$_.PSIsContainer -and !($_.FullName.Replace($loc,"") -like "*scripts\*") }

多个文件夹(这很难看):

#Don't include "\" at the end of $loc - it will stop the script from matching first-level subfolders
$loc = "C:\tools\scripts\myscripts"
$ignore = @("testfolder1","testfolder2");

$files = Get-ChildItem -Path $loc -Recurse -Exclude *.docx, *.xlsx | ? { !$_.PSIsContainer } | % { $relative = $_.FullName.Replace($loc,""); $nomatch = $true; foreach ($folder in $ignore) { if($relative -like "*\$folder\*") { $nomatch = $false } }; if ($nomatch) { $_ } }

答案 1 :(得分:0)

如果我理解了这个问题,那你就走上了正确的道路。要排除* .docx文件和* .xlsx文件,您需要将它们作为过滤字符串数组提供给-exclude parm。

$files = Get-ChildItem -Path $loc -Recurse -Exclude @('*.docx','*.xlsx') | ? { !$_.PSIsContainer }

答案 2 :(得分:0)

我也试图这样做,Graimer的答案不起作用(方式太复杂了),所以我想出了以下内容。

$ignore = @("*testfolder1*","*testfolder2*");
$directories = gci $loc -Exclude $ignore | ? { $_.PSIsContainer } | sort CreationTime -desc

答案 3 :(得分:0)

在PowerShell的第3版中,我们可以告诉Get-ChildItem只显示如下文件:

PS> $files = Get-ChildItem -File -Recurse -Path $loc 

如果您只想收集某些文件名(例如abc * .txt),您还可以使用过滤器:

PS> $files = Get-ChildItem -File -Recurse -Path $loc -Filter abc*.txt
相关问题