【问题标题】:Exclude all sub-directories from PowerShell Get-ChildItem -match从 PowerShell Get-ChildItem -match 中排除所有子目录
【发布时间】:2018-11-20 05:38:22
【问题描述】:

目标

在运行与文件名正则表达式模式匹配的 PowerShell 脚本时排除所有子目录

目录结构

/
- 2018-11-19.md

18-2/
- 2018-10-16.md
- 2019-01-14.md
- 2019-10-10.md

18-3/
- 2019-01-13.md
- 2019-04-25.md

PowerShell 脚本

$file = '2018-11-19.md'

Get-ChildItem -recurse | where-object { $_.FullName -match '[0-9]{4}-[0-9]{2}-[0-9]{2}.md' } | 
    ForEach-Object {$fullname = $_.fullname; (Get-Content $_.fullname | foreach-object {
        $_ -replace "apple", "orange"
    }) | Set-Content $fullname}

(Get-Content $file | ForEach-Object {
        $_ -replace '<p(.*?)>(.*?)</p>', '$2'
    }) | Set-Content -Encoding Utf8 $file

Get-ChildItem -recurse | where-object { $_.FullName -match '[0-9]{4}-[0-9]{2}-[0-9]{2}.md' } | 
    foreach-Object {$fullname2 = $_.fullname; (Get-Content $_.fullname | 
         pandoc -f markdown -t markdown -o $fullname2 $fullname2
    )}

详情

  • 目标是仅在根目录中的文件上运行 PowerShell 脚本。根目录中的这些文件将更改,但始终根据所示约定命名。 PowerShell 脚本中的正则表达式成功匹配此文件名。
  • 目前脚本会更改上述目录示例中的所有文件
  • 我能找到的任何示例都显示了如何通过在脚本中识别特定目录的名称来排除特定目录(例如,-Exclude folder-name)。我想排除 所有 子目录而不专门命名它们,因为...
  • ...将来可能会为 18-4、19-5 等添加子目录,因此基于正则表达式的排除似乎是有意义的。

尝试

为了将脚本的作用域限制在根目录,我尝试了-notmatch\\*\*.*\\* 等的变体,但没有成功。

为了排除子目录,我在-Exclude 上尝试了相同路径的变体,但没有成功。

我的 PowerShell 知识还不够先进,无法走得更远。我将不胜感激任何帮助或指出正确的方向。感谢您的帮助。

【问题讨论】:

  • 如果您只想要脚本开始的根目录,只需删除 Get-Childitem 上的 -recurse 标志
  • “仅在根目录中的文件上”。 “仅文件” = '-Files 开启 Get-ChildItem。 “根目录” = 不要使用-Recurse

标签: powershell


【解决方案1】:

正如 Owain 和 gvee 在 cmets 中所指出的,当使用 -Recurse 开关时,您告诉 Get-ChildItem cmdlet 您希望从所选位置遍历子目录结构。 As expained on the docs site of the cmdlet

Gets the items in the specified locations and in all child items of the locations.

因此,只需删除开关即可使代码按您的意愿运行。 如果您只想要 X 级子目录,您可以使用 -Depth 开关。

Get-ChildItem | where-object { $_.FullName -match '[0-9]{4}-[0-9]{2}-[0-9]{2}.md' } | 
    ForEach-Object {$fullname = $_.fullname; (Get-Content $_.fullname | foreach-object {
        $_ -replace "apple", "orange"
    }) | Set-Content $fullname}

(Get-Content $file | ForEach-Object {
        $_ -replace '<p(.*?)>(.*?)</p>', '$2'
    }) | Set-Content -Encoding Utf8 $file

Get-ChildItem | where-object { $_.FullName -match '[0-9]{4}-[0-9]{2}-[0-9]{2}.md' } | 
    foreach-Object {$fullname2 = $_.fullname; (Get-Content $_.fullname | 
         pandoc -f markdown -t markdown -o $fullname2 $fullname2
    )}

【讨论】:

  • 这很容易。谢谢@Henrik Stanley Mortensen
猜你喜欢
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2018-08-22
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多