-match results (Get different behavior)

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of 84rusty . 84rusty . 2 months, 3 weeks ago.

  • Author
    Posts
  • #54238
    Profile photo of Andrew
    Andrew
    Participant

    I've been looking at the -match operator which as I understand returns a Boolean – True / False. I have found that if I use this in some situations it returns the matching item rather than a Boolean. It seems to change behavior if it is used with an object array.

    Can someone assist explaining what lies behind this change in behavior.

    Example for testing – trying to extract a Version ID stored in a text file

    #Path to product details file for testing
    $path = 'C:\temp\productID.txt'

    #Load the contents of product into the variable $Details
    $Details =get-content -Path $path

    #Select the line that contains Versionid (In this format: VersionId : 6cccd490-8861-4118-97f6-3asdjkfua7a4f7)
    $Verid=($Details -match "VersionId")

    It seems that I get back $Verid = VersionId : 6cccd490-8861-4118-97f6-3asdjkfua7a4f7 rather than True or false? Thought I should get back a Boolen here??

    I can then use the split operator
    $Verid.Split()[-1]

  • #54239
    Profile photo of 84rusty .
    84rusty .
    Participant

    If the text file is a single line, then when you run Get-Content, it stores that single line as a string, and the -match operator returns true or false.

    If the text file is multi-lined, then when you run Get-Content, the lines are stored as an array and when you use the -match operator, it provides the line that matches the condition, as if you're saying 'get me the line from this array that matches VersionID'.

    You need to step into the array, and process each line as follows:

    $details = Get-Content -path $path
    ForEach($detail in $details){
        If($detail -match '^VersionID'){
            Write-host "$detail"
        }
    }
    
    • This reply was modified 2 months, 3 weeks ago by Profile photo of 84rusty . 84rusty ..

You must be logged in to reply to this topic.