powershellexpressionselect-string

Use Select-String to get the single word matching pattern from files


I am trying to get only the word when using Select-String, but instead it is returning the whole string

Select-String -Path .\*.ps1 -Pattern '-Az' -Exclude "Get-AzAccessToken","-Azure","Get-AzContext"

I want to get all words in all .ps1 files that contain '-Az', for example 'New-AzHierarchy'


Solution


  • Therefore:

    # Note: -AllMatches ensures that if there are *multiple* matches 
    #        on a single line, they are all reported.
    Select-String -Path .\*.ps1 -Pattern '\w+-Az\w+' -AllMatches |
      ForEach-Object { $_.Matches.Value } |
      Where-Object { $_ -notin 'Get-AzAccessToken', '-Azure', 'Get-AzContext' }