【问题标题】:Powershell : Match file name with folder namePowershell:将文件名与文件夹名匹配
【发布时间】:2014-08-28 12:08:44
【问题描述】:

我正在尝试将文件名与文件夹名匹配,然后再将它们移动到其他目录。

例如,如果“Test.txt”与名为“Test”的文件夹匹配,我的脚本需要匹配并将它们移动到不同的目录。

是否可以使用 cmdlet Get-ChildItem ?我没有找到任何例子:(

非常感谢。

【问题讨论】:

  • Get-ChildItem 使您能够列出(递归或不递归)指定目录的内容。然后您可以检查是否存在与您的文件名称相同的目录。 (Get-Help Test-Path应该有点帮助)

标签: powershell directory filenames


【解决方案1】:

PowerShell 3+

从当前目录递归获取所有文件名(无扩展名)与其目录名匹配的文件:

Get-ChildItem -Path . -File -Recurse |
    Where-Object { $_.BaseName -eq $_.Directory.Name }

PowerShell 1、2

在 PowerShell 3 之前没有 -File 开关,因此您必须使用额外的 Where-Object 过滤掉目录。

Get-ChildItem -Path . -Recurse |
    Where-Object { -not $_.PsIsContainer } |
    Where-Object { $_.BaseName -eq $_.Directory.Name }

获得与其父目录名称匹配的所有文件后,您应该能够移动它们。我不确定目标目录结构的逻辑是什么。

【讨论】:

    【解决方案2】:

    对于初学者,您可以使用Get-ChildItemDirectory 属性

    假设您正在寻找一个文件test.txt,但前提是它位于目录Scripts

    Get-ChildItem *.txt -recurse | Where-Object{($_.Name -eq "test.txt") -and ($_.Directory -like "*\scripts")} | Move-Item $_.Directory "C:\NewFolder"
    

    Where 子句将在名为 text.txt 的文件夹中查找名为 text.txt 的文件。所以这将不匹配c:\anotherpath\test.txt。找到匹配项时 将找到的files 目录移动到新位置。

    注意如果找到多个文件匹配,我不确定逻辑是否成立。如果失败,那么我们可以将所有匹配项分配给一个变量,然后处理所有唯一值。

    $foundDirectories = Get-ChildItem *.txt -recurse | Where-Object{($_.Name -eq "test.txt") -and ($_.Directory -like "*\scripts")} | Select-Object -ExpandProperty Directory -Unique
    $foundDirectories | ForEach-Object{Move-Item $_ "C:\newfolder"}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      相关资源
      最近更新 更多