How to filter list depending on occurences within string

Viewed 34

I have an array of items like this:

get-childitem *\bin\Release\*Tests.dll -recurse

I have paths like these:

C:\r\x\ABCTests\bin\Release\net461\ABCTests.dll
C:\r\x\ABCTests\bin\Release\net461\OtherTests.dll
C:\r\x\OtherTests\bin\Release\net461\OtherTests.dll

I only want the paths that the name of the file matches the name of the folder:

C:\r\x\ABCTests\bin\Release\net461\ABCTests.dll - Yes
C:\r\x\ABCTests\bin\Release\net461\OtherTests.dll - No
C:\r\x\OtherTests\bin\Release\net461\OtherTests.dll - Yes

What would be the best way to filter this in Powershell? I have tried with Select-String but it opens the file. I have the regex expression ready for I'm having trouble in executing in in Powershell. Should I use regex?

Here is the powershell code:

get-childitem *\bin\Release\*Tests.dll -recurse | Where-Object { $_.FullName -match {"(" + $_.Name.Substring(0, $_.Name.LastIndexOf(".")) + ").*\1\.dll"} } | %{ write-host $_ }
1 Answers

I suggest using

$rx = '\\([^\\]*)Tests\\bin\\Release\\(?:.*\\)?\1Tests\.dll$'

See the regex demo.

Regex details

  • \\ - a \ char
  • ([^\\]*) - Group 1: any zero or more chars other than a backslash
  • Tests\\bin\\Release\\ - a Tests\bin\Release\ text (we may hardcode it since this value was used in the glob)
  • (?:.*\\)? - an optional sequence of any 0 or more chars other than a newline as many as possible, and then a backslash
  • \1 - the same value as captured in Group 1
  • Tests\.dll - Tests.dll string (we may hardcode it since this value was used in the glob)
  • $ - end of string.

Then use

Get-Childitem *\bin\Release\*Tests.dll -recurse | 
  Where { $_.FullName -match $rx } | 
    % { $_.FullName }

See the regex demo.

Related