Using PowerShell, I need to get the first instance of a match from each (text) file in the directory.
The relevant section of the file looks like this:
TANK PRODUCT VOLUME TC-VOLUME ULLAGE HEIGHT WATER TEMP
1 Unleaded 2275 0 7606 34.83 0.00 70.12
Further down in the file, there are more instances of the word "Unleaded", but I need to get the Volume (2275 in this case) from this line.
This script: $u_line = (Select-String -Path ".\TMUSite_*.sav" -Pattern "Unleaded" | Select-Object * -First 1).Line Gets me: 1 Unleaded 2275 0 7606 34.83 0.00 70.12
... and that's fine because I can pull the number out of there with a [regex]::matches, or something. The problem is that there are about 10 files in the directory and I need to get this value out of all of them. Right now I only get the match from the first file.
I was expecting to get an array of lines similar to above. I thought the "-First 1" was getting me the first match and that this would happen for each file. The benefit of using Select-String is the object that it returns, in that it includes the file name which has an ID in it that I have to tie the extracted values to, probably in a PSCustomObject. But for now I can only get that first line.
I thought the "-First 1" was getting me the first match and that this would happen for each file.
No, it gets only the first output object overall, across all files.
Also note that you don't need Select-Object *
(short for: Select-Object -Property *
with -First
; in fact, if you do so, you unnecessarily create copies of Select-String
's output objects.
Instead, use Select-String
's -List
switch to limit output to one match per file.
Select-String -List -Path ".\TMUSite_*.sav" -Pattern "Unleaded"