Reputation: 4736
How do I pull text between two words? I know regex can do this and I have been looking around but the code I try just does not work for me at all...as clueless as a brick with regex...so probably am doing it totally wrong...
I have a text file and want to query whatever is displayed between these text strings:
[Problem Devices]
Device PNP Device ID Error Code
[USB]
I tried doing this but getting no where!
$devices = Get-Content c:\temp\dev.txt | out-string [regex]::match($devices,'(?<=\<Problem Devices\>).+(?=\<USB\>)',"singleline").value.trim()
You cannot call a method on a null-valued expression.
At line:1 char:141
+ $devices = Get-Content c:\temp\dev.txt | out-string [regex]::match($devices,'(?<=\<Problem Devices\>).+(?=\<USB\>)',"
singleline").value.trim <<<< ()
+ CategoryInfo : InvalidOperation: (trim:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Upvotes: 1
Views: 3486
Reputation: 68331
If you're not comfortable with regex, there are other ways:
$test = $false
$devices = get-content file.txt |
foreach {
if ($_.trim() -eq '[Problem Devices]'){$test = $true}
elseif ($_.trim() -eq '[USB]') {$test = $false}
elseif ($test){$_}
} | where {$_.trim()}
Upvotes: 0
Reputation: 28194
Piping to out-string
is not needed; get-content
is sending each line of the file into the pipeline as a separate object. So you want to iterate through those objects with a foreach-object
.
$devices = Get-Content c:\temp\dev.txt | foreach-object{[regex]::match($devices,'(?<=\<Problem Devices\>).+(?=\<USB\>)',"singleline").value.trim()}
However, you are still left with the problem of attempting to trim()
a null
object - if your regex match doesn't find a match, you can't call value.trim()
.
Your regex tries to match on <Problem Devices>
when your input file has [Problem Devices]
.
Rather than try to do everything in a single set of pipeline steps, break your problem down:
PSObjects
(one per device), or a collection of hashes (one per device), depending on your needs).Upvotes: 1