Question

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
Was it helpful?

Solution

-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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top