Search code examples
regexpowershellplex

Regex with powershell


I am writing a powershell script to notify me if two users are using the same username but different IP when playing from a plex server.

I managed to get an xml display of current connections that are steaming at that time.

What I need to do is to come up with a reg expression where I extract the User id and IP address and then I can do a search to see if there are duplicate user ID and that has different IP.

I managed to find the regex for IP addresses which is '\b\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}\b’

But having a hard time to extract the User Id from it as well. Note the User ID will always be numbers but no set limit.

Here is the example of the data

<User id="13456" title="usersmith" />
<Player address="2.2.2.2" device="Windows" machineIdentifier="a9b222ef940" 

Solution

  • I would parse this as xml, ex:

    #$xml = [xml](Get-Content myfile.xml)
    #$xml = [xml](Invoke-WebRequest ... whatever).Content
    $xml = [xml]@"
    <?xml version="1.0" encoding="utf-8"?>
    <root>
    <User id="13456" title="usersmith" />
    <Player address="2.2.2.2" device="Windows" machineIdentifier="a9b222ef940" />
    </root>
    "@
    
    $xml.root.user.id
    

    but if you really want regex, try @heemayl's solution except the start-of-line ^-anchor which might not fit your real xml-data (in that case you've provided bad sampledata). Ex:

    if('User id <User id="1354" thumb="plex.tv/users/a51d"; title="bob" />' -match '<User\s+id="([^"]+)"') { $Matches[1] }