【问题标题】:How to use -Exclude to exclude all the contents of a specific folder in PowerShell?如何使用 -Exclude 排除 PowerShell 中特定文件夹的所有内容?
【发布时间】:2021-07-05 08:20:32
【问题描述】:

想要获取tree 文件夹的所有内容,L1 子文件夹 [^1] 除外。

在当前情况下有两个文件,fill.txtdbg.log

本来我想用-Exclude,但是尝试了很多用法都无法实现。

# I don't know why the exclude parameter doesn't seem to work
Get-ChildItem -Recurse -Path 'tree' -Exclude 'tree\L1' | Should -Not -HaveCount 2
Get-ChildItem -Recurse -Path 'tree' -Exclude 'tree\L1\*' | Should -Not -HaveCount 2
Get-ChildItem -Recurse -Path 'tree' -Exclude "$('tree\L1'|Resolve-Path)*" | Should -Not -HaveCount 2

Where-Object作品:

Get-ChildItem -Recurse -Path 'tree' | Where-Object {
    [string]$_ -notlike "$('tree\L1'|Resolve-Path)*"
} | Should -HaveCount 2

我使用Exclude参数的方式有什么问题?如何纠正?

补充:这只是一个案例。我想知道如何使用-Exclude 参数来做到这一点。

[^1]:

\tree
├──L1
│  ├──L2
│  │  ├──L3
│  │  │  ├──300.txt
│  │  │  └──xtf.log
│  │  ├──L3_1
│  │  │  ├──123.fp
│  │  │  └──dbg.log
│  │  ├──300.txt
│  │  └──xtf.log
│  ├──L2_1
│  │  ├──150.txt
│  │  └──15x.txt
│  ├──L2_2
│  │  ├──dbg_2.log
│  │  └──dbg.log
│  └──tl.txt
├──dbg.log
└──fill.txt

【问题讨论】:

  • 在您的 tree 结构中,所有内容都在 L1 文件夹中,而不仅仅是您提到的两个文件。这是否意味着您只想列出 L1 的子文件夹及其子文件夹,但是不是直接在 L1 中的文件?
  • @Theo No.我要做的是在第二个代码段中。那些代码运行的结果是正确的。
  • -Exclude-Include 仅处理项目的名称,而不是完整路径。您可以尝试Get-ChildItem -Recurse -Path 'tree' -Exclude 'L1',但这也会排除子目录中恰好名为L1..的项目。如果这是可行的,我会坚持使用Where-Object子句。
  • Get-ChildItem tree -Recurse -Exclude l1,tl.txt 应该会给您预期的结果,但正如 Theo 所提到的,如果有一个项目(子文件夹/存档)完全命名为 L1tl.txt,那么您也将排除这些项目。

标签: powershell powershell-core


【解决方案1】:

正如 cmets 中已经提到的,您想要一些使用 -Exclude 参数无法实现的东西。

此参数仅对项目名称起作用。不幸的是,官方文档没有很好地记录这个问题。

【讨论】:

    猜你喜欢
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 2012-09-19
    • 2018-12-11
    • 1970-01-01
    • 2021-08-16
    • 2017-09-02
    相关资源
    最近更新 更多