Powershell-排除Get ChildItem中的文件夹
如何排除文件夹?现在我硬编码文件夹名称,但我希望它更灵活Powershell-排除Get ChildItem中的文件夹,powershell,Powershell,如何排除文件夹?现在我硬编码文件夹名称,但我希望它更灵活 foreach($file in Get-ChildItem $fileDirectory -Exclude folderA,folderb) 您可以通过使用管道和Where对象过滤器来实现这一点 首先,在PowerShell中迭代一组文件的惯用方法是通过管道Get Childitem到Foreach对象。因此,重写命令会得到: Get-ChildItem $fileDirectory | foreach { $file = $_
foreach($file in Get-ChildItem $fileDirectory -Exclude folderA,folderb)
您可以通过使用管道和
Where对象
过滤器来实现这一点
首先,在PowerShell中迭代一组文件的惯用方法是通过管道Get Childitem
到Foreach对象
。因此,重写命令会得到:
Get-ChildItem $fileDirectory | foreach {
$file = $_
...
}
使用管道的优点是,现在可以在两者之间插入其他cmdlet。具体来说,我们使用Where Object
来过滤文件列表。仅当文件未包含在给定数组中时,筛选器才会传递该文件
$excludelist = 'folderA', 'folderB'
Get-Childitem $fileDirectory |
where { $excludeList -notcontains $_ } |
foreach {
$file = $_
...
}
如果要经常使用此功能,甚至可以编写自定义筛选函数,在传递到foreach
之前以任意方式修改文件列表
filter except($except, $unless = @()) {
if ($except -notcontains $_ -or $unless -contains $_ ){
$_
}
}
$excludelist = 'folderA', 'folderB'
$alwaysInclude = 'folderC', 'folderD'
Get-ChildItem $fileDirectory |
except $excludeList -unless $alwaysInclude |
foreach {
...
}
“如何排除文件夹?”,如果您是指所有文件夹:
get-childitem "$fileDirectory\\*" -file
但它仅适用于$fileDirectory的第一级。
这是递归的:
Get-ChildItem "$fileDirectory\\*" -Recurse | ForEach-Object { if (!($_.PSIsContainer)) { $_}}
或
@dvjz说-file只在文件夹的第一级工作,而不是递归的。但它似乎对我有用
get-childitem "$fileDirectory\\*" -file -recurse
递归排除文件夹的最简单方法:
foreach($file in Get-ChildItem $fileDirectory -Exclude {**Get-ChildItem folderA**},{**Get-ChildItem folderb**})
如果我没有错,这仍然需要指定要排除的文件夹名称。例如,如果我有100个文件夹,我需要将每个文件夹指定100次。现在,我想跳过这个手动过程。您需要构建一个文件夹列表,以某种方式排除这些文件夹,无论是手动还是运行另一个
getchilditem
命令。这取决于您如何选择要排除的文件夹。是否要排除所有文件夹?或者只是您选择的路径?我理解这个问题的意思是获取文件路径列表,而不仅仅是文件夹的路径(.例如,不要list/folder1/subfolder,而是list/folder1/subfolder/log.txt)。这似乎对我更有效:get ChildItem-Recurse-文件|解析路径
或相对路径:获取子项-递归-文件|解析路径-相对
foreach($file in Get-ChildItem $fileDirectory -Exclude {**Get-ChildItem folderA**},{**Get-ChildItem folderb**})