powershell - Exclude one folder and a filetype from Get-childitem
问题描述
I have a website that needs frequent backup hence I would like to write a script to compress all the files in the screenshot. Except:
- All the contents in the image folder (See Highlighted)
- Any *.log files in the entire directory
I tried to get a list of files and always end up having the image folders contents:
$WebAppFolder = 'C:\ReleaseBackupScript\MyWebSite'
$filteredList = Get-childitem -path $WebAppFolder -exclude $WebAppFolder"\image",*.log -Name -recurse -force
Out-File -FilePath FilteredList.txt -InputObject $filteredList
解决方案
As Theo notes, as of as of PowerShell 7.2:
-Exclude
(as well as-Include
and-Filter
) operate on file and directory names only, not on paths.Similarly,
-Exclude
doesn't support excluding entire directory subtrees (a directory and all its content).
Overcoming these limitations in a future PowerShell version for -Include
and -Exclude
is being discussed in GitHub issue #15159.
Therefore, you'll have to perform your own post-filtering yourself:
$WebAppFolder = 'C:\ReleaseBackupScript\MyWebSite'
$filteredList =
Get-ChildItem -Recurse -Force -File -Name -LiteralPath $WebAppFolder -Exclude *.log |
Where-Object { $_ -notlike 'image\*' } > FilteredList.txt
Note: Since you're using Get-ChildItem
's -Name
parameter, the output objects are strings, namely relative paths, which is why each input object to the Where-Object
script block (reflected in automatic $_
variable) is matched as whole against a wildcard expression that matches strings that start with image\
.
Without -Name
, System.IO.FileInfo
instances would be output, in which case you'd have to use the following filter command:
Where-Object { $_.FullName -notlike '*\image\*' }
or - using Where-Object
's simplified syntax:
Where-Object FullName -notlike *\image\*
Note that, as of PowerShell 7.2, simplified syntax is currently not available for operations performed on the input object as a whole, because the name of a property to operate on is required. That is,
Where-Object -notlike *\image\*
- with the LHS operand implicitly being the whole input object ($_
) - does not work, though supporting that is being discussed in GitHub issue #8357.
推荐阅读
- python - Numpy添加给定的行
- shell - jq 具有来自不同来源的多个输入
- android - 使用 android 媒体播放器播放音频文件
- asp.net-mvc - 在表 'XXX' 上引入 FOREIGN KEY 约束 'XYZ_ID' 可能会导致 mvc 核心中出现循环或多个级联路径
- postgresql - PostgreSQL 大查询优化
- javascript - 按索引上下移动数组对象/元素
- java - 可以使用什么来代替共享首选项来存储用户信息?正如人们所说,共享首选项不安全
- python - Airflow 中的成功邮件
- java - map()/mapPartition() 输出记录数是否应该与输入记录数匹配?
- ios - Obj-c 或 Swift 中是否有 Griddata 或 ScatteredInterpolant 的等价物?