我编写了一个脚本,它将递归指定的文件夹并对其中的文件进行一些分析。我需要在分析中排除指定的子文件夹。此排除列表会根据正在分析的基本文件夹而变化。我的脚本使用这样的长模式:
Get-ChildItem -File -Recurse $source_folder |
Where-Object {
$_.FullName -notlike "*\folder_name0\*" -and
$_.FullName -notlike "*\folder_name1\*" -and
$_.FullName -notlike "*\folder_name2\*" -and
$_.FullName -notlike "*\folder_name3\*" -and
$_.FullName -notlike "*\folder_name4\*"
}
Run Code Online (Sandbox Code Playgroud)
但这不太可重用。我希望能够将例外列表存储在 .CSV 中,并根据我正在分析的文件夹集调用我需要的例外列表。我想做的是这样的:
$exception_list = Import-CSV .\exception_list
Get-ChildItem -File -Recurse $source_folder |
Where-Object {$_.FullName -notlike $exception_list}
Run Code Online (Sandbox Code Playgroud)
但这不起作用。我怀疑是因为我无法在数组中的元素之间指定“and”或“or”。我确实短暂地考虑过尝试使用 a 即时创建整个参数foreach($exception in $exception_list){$argument += "$_.FullName -notlike $exception -and"}
,但这很快就变得愚蠢和复杂,因为您仍然需要删除最后一个“和”。
有没有有效的方法来做到这一点?
这构建了要排除的部分名称的数组,并使用该数组构建正则表达式 OR 以在测试中使用-notmatch
。
$ExcludedDirList = @(
'PSES-'
'vscode'
'Test_'
)
# regex uses the pipe symbol as the logical "OR"
$RegexExcludedDirList = $ExcludedDirList -join '|'
$Results = Get-ChildItem -Path $env:TEMP -File -Recurse |
Where-Object {
$_.DirectoryName -notmatch $RegexExcludedDirList
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2051 次 |
最近记录: |