I appreciate your desire to understand. I hate to steal Fer’s thunder but I can explain it for you. Having said that Olaf is right about pure PowerShell although Split-Path isn’t needed for the data you desire. Select-String returns a “MatchInfo” object that has not only a Path property but also a Filename property which is what you are looking for.
Select-String -Path “C:\Users\spate\Documents\sample*.txt” -Pattern ‘server one’ |
Select-Object -ExpandProperty Filename
The key here is PowerShell is an object oriented scripting language. Just because a cmdlet returns “default” information to the screen based on the object type, that is NOT the full object. If you pipe the results to Get-Member, you’ll see all the available properties and methods.
Fer used the substring method of the string object. The substring method can take 1 or 2 arguments. In this case he passed two arguments. The first is the starting index, the second is how many characters to return.
For the starting index, he used:
$String.LastIndexOf('\') + 1
This is calling the LastIndexOf method which does exactly what the name implies, returns the last index of the character specified. In this case, it is returning the index (position) of the last \ then adding 1 to it so it starts at the very next character.
For how many characters to return (2nd argument of the SubString method), he used:
($String.LastIndexOf(':') - $String.LastIndexOf('\') - 3)
The same LastIndexOf method is used here to determine how long the filename is. The flaw in this is that it expects the results to always have a single character following the first : but if your files have more than 9 lines of text and the search finds your criteria on line 10, then this would be off.