简体   繁体   中英

Powershell : Match file name with folder name

I'm trying to match file name with folder name before move them to an other directory.

For example, my script need to match if "Test.txt" match with a folder named "Test" and move them to a different directory.

Is it possible with the cmdlets Get-ChildItem ? I didn't find any examples :(

Thanks a lot.

PowerShell 3+

Gets all files recursively from the current directory whose names (without extension) matches its directory's name:

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

PowerShell 1, 2

There is no -File switch until PowerShell 3, so you have to filter out directories with an extra Where-Object .

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

Once you've got all the files that match their parent directory name, you should be able to move them. I'm not sure what your logic is for the destination directory structure.

For starters you can use the Directory property of Get-ChildItem

So lets say you are looking for a file test.txt but only if it is in the directory Scripts

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

The Where clause will look for a file called text.txt as long as its in a folder called c:\\somepath\\scripts . So this will not match c:\\anotherpath\\test.txt . When a match is found Move the located files directory to a new location.

Note I am not sure if the logic will hold if multiple file matches are found. If it fails then we could assign all the matches to a variable and then process the all the unique values.

$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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM