Powershell:将文件名与文件夹名匹配

时间:2014-08-28 12:08:44

标签: powershell directory filenames

我正在尝试将文件名与文件夹名称匹配,然后再将其移至其他目录。

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

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

非常感谢。

2 个答案:

答案 0 :(得分:3)

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 }

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

答案 1 :(得分:0)

对于初学者,您可以使用Directory

Get-ChildItem属性

因此,假设您正在查找文件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的文件夹中查找名为c:\somepath\scripts的文件。所以这与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"}
相关问题