C:\Users\spate\Documents\SampleFile.txt:1:Server one
C:\Users\spate\Documents\SampleFile10.txt:1:Server one
C:\Users\spate\Documents\SampleFile3.txt:1:Server one
C:\Users\spate\Documents\SampleFile4.txt:1:Server one
But then I want to extract only “SampleFile*” to another variable
Couple of ways using regex after you have your strings. You could probably incorporate in the original select-string but I’m not sure what’s going on before then.
$str = @'
C:\Users\spate\Documents\SampleFile.txt:1:Server one
C:\Users\spate\Documents\SampleFile10.txt:1:Server one
C:\Users\spate\Documents\SampleFile3.txt:1:Server one
C:\Users\spate\Documents\SampleFile4.txt:1:Server one
'@
$str -replace '(?m)^.+\\|:.+$'
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.
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:
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.