PowerShell: Find exact folder name
Asked Answered
I

1

8

I'm trying to find a way to return the full path to a given folder. The problem is that my code returns more than one folder if there is a similar named folder. e.g. searching for "Program Files", returns "Program Files" and "Programs Files (x86)". As I didn't ask for "Program Files (x86), I don't want it to return it. I am using:

$folderName = "Program Files"
(gci C:\ -Recurse | ?{$_.Name -match [regex]::Escape($folderName)}).FullName

I thought of replacing -match with -eq, but it will return $false as it's comparing the whole path.

I have thought of maybe returning all matches, then asking the user to select which one is correct, or creating an array that splits the path down and doing an -eq on each folder name and then joining the path again, but my skills are lacking in the array department and cannot get it to work.

Any help or pointers would be gratefully received.

Thanks

Here's what I have used with thanks to Frode:

$path = gci -Path "$drive\" -Filter $PartialPath -Recurse -ErrorAction SilentlyContinue #| ?{$_.PSPath -match [regex]::Escape($PartialPath)} 

($path.FullName | gci -Filter $filename -Recurse -ErrorAction SilentlyContinue).FullName
Insatiable answered 2/3, 2014 at 11:59 Comment(0)
E
10

-match is like asking for *Program Files*. You should be using the -Filter parameter of Get-ChildItem for something like this. It's a lot faster and doesn't require regex escape etc.

PowerShell 3:

$folderName = "Program Files"
(gci -path C:\ -filter $foldername -Recurse).FullName

PowerShell 2:

$folderName = "Program Files"
gci -path C:\ -filter $foldername -Recurse | Select-Object -Expand FullName

Also, you should not use -Recurse if you don't need it(like in this example).

Eddy answered 2/3, 2014 at 12:40 Comment(2)
Thank you Frode. I also needed to return the FullName of a specific file, hence the posted use of GCI. With your help I can do it this way: Can it be simplified?Insatiable
$path = gci -Path "$drive\" -Filter $PartialPath -Recurse -ErrorAction SilentlyContinue ($path.FullName | gci -Filter $filename -Recurse -ErrorAction SilentlyContinue).FullName.Insatiable

© 2022 - 2024 — McMap. All rights reserved.