1

I am trying to run a powershell command to return a SID from a string.

$string = "The SID is S-1-9-1551374245-3853148685-361627209-2951783729-4075502353-0-0-0-0-3"

Select-String -Pattern "\bS-\d{1}-\d{1}-\d{10}-\d{10}-\d{9}-\d{10}-\d{10}-\d{1}-\d{1}-\d{1}-\d{1}-\d{1}\b" -InputObject $string 

when I run the above, it returns the whole string but I only want the SID # which is 'S-1-9-1551374245-3853148685-361627209-2951783729-4075502353-0-0-0-0-3'

Thyrus017
  • 43
  • 2
  • 11
  • `$res = [regex]::match($string,'\bS-\d-\d(?:-\d{10}){2}-\d{9}(?:-\d{10}){2}(?:-\d){5}\b').Value` – Wiktor Stribiżew Sep 20 '19 at 23:31
  • 1
    your problem is that you are using `Select-String` that `gasp! arg!` **_selects strings_**. [*grin*] either pull the match out of the `MatchInfo` object OR use normal regex with `-match` and get the value from the `$Matches` automatic variable. – Lee_Dailey Sep 20 '19 at 23:55
  • taking a slightly different approach ... is the sample data you posted accurate? if it is, then you can simply use `.Split(' ')` and select the last item in the resulting array. – Lee_Dailey Sep 20 '19 at 23:56
  • Where did you get the string from? – js2010 Sep 22 '19 at 08:33

4 Answers4

4

You can try the following regex:

S-\d-(?:\d+-){1,14}\d+

Regex Demo

Explanation:

S-              # Match S- literally
\d-             # Match a digit- literally
(?:\d+-){1,14}  # Non-capturing group to match recursively digit- from 1-14 times
\d+             # Match digit recursively
vs97
  • 5,765
  • 3
  • 28
  • 41
4
$Pattern = 'S-\d-(?:\d+-){1,14}\d+'
$Matches =  Select-String -Pattern $Pattern -InputObject $string
if ( $Matches ) { $Matches.Matches.Value }

Credit for vs97's regex pattern

JosefZ
  • 28,460
  • 5
  • 44
  • 83
1

As shown in JosefZ's helpful answer, your only problem was that you didn't extract the match of interest from the properties of the [Microsoft.PowerShell.Commands.MatchInfo] object that your Select-String call outputs.

However, using a cmdlet is a bit heavy-handed in this case; the -replace operator offers a simpler and better-performing alternative:

$string = "The SID is S-1-9-1551374245-3853148685-361627209-2951783729-4075502353-0-0-0-0-3"

$string -replace `
  '.*\b(S-\d-\d-\d{10}-\d{10}-\d{9}-\d{10}-\d{10}-\d-\d-\d-\d-\d)\b.*', 
  '$1'

I've simplified your regex a bit: \d{1} -> \d. Note that it doesn't match all possible forms that SIDs can have.

Note how the regex matches the entire input string, and replaces it with just the what the capture group ((...), the subexpression matching the SID) matched ($1).

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Your expression seems to be just fine, maybe a bit modification,

\bS(?:-\d){2}(?:-\d{10}){2}-\d{9}(?:-\d{10}){2}(?:-\d){5}\b

would be OK, other than that it should have worked though.

Demo 1

Or with a lookbehind:

(?<=The SID is )\S+

Demo 2

Emma
  • 27,428
  • 11
  • 44
  • 69