powershellselect-stringselect-object

PowerShell code returning more values than expected


Good evening. Stack Overflow and Powershell novice here.

The below piece of code in Powershell is returning more values than I wanted. For example, it is capturing variables in a JSON file that match PPVCOUNT but also variables named with characters before and after the PPVCount string. Example:

PPVCountAtInception

OperatorCountGreaterThanPPVCountIndicator

GOAL: My goal is to have the code only return the variable PPVCount. I also want to keep the columns: Pattern, LineNumber, Line. Forgive me for my lack of knowledge and thank you in advance

$file = 'C:\\Users\\B187515\\Downloads\\j.json'
$PPVCount="PPVCount"

Get-Content $file | Select-String -Pattern $PPVCount -Context 1| Select-Object Pattern,LineNumber, Line -ExpandProperty Context -First 18 | Format-Table | Out-file -FilePath 'C:\\Users\\B187515\\Downloads\\test.csv' -Append

Expected results:

My goal is to have the code only return the variable "PPVCount" in the CSV file. I also want to keep the columns: Pattern, LineNumber, Line

Actual results There are multiple variables returning contain "PPVCount" somewhere in the variable name. See screenshot of CSV enter image description here


Solution

  • Building on the helpful comments:

    # Note: Just use '\' - no need for '\\'
    $file = 'C:\Users\B187515\\Downloads\j.json'
    
    # Enclose the property name to search for in embedded "..."
    $searchRegex ='"PPVCount"'
    
    # Pass $file (the file to search through) directly to Select-String, 
    # and use Export-Csv to export the results to a CSV file.
    Select-String -LiteralPath $file -Pattern $searchRegex -Context 1 | 
      Select-Object Pattern, LineNumber, Line -ExpandProperty Context -First 18 | 
      Export-Csv -LiteralPath 'C:\Users\B187515\Downloads\test.csv'