Grabbing an Activation ID key after first instance of a text string using Slmgr /dlv and Regex?

Viewed 242

Slmgr /dlv gives a list of licenses on any given computer. One is for the OS, one is called an "ESU" key, there are others depending on your system. I'm attempting to grab the first instance of an Activation ID that comes after the text "ESU", so I'm not grabbing the OS Activation key or any other for that matter.

With this code, I think it's grabbing the second instance of Activation ID after the text "ESU" or it's just grabbing the wrong key altogether. What am I doing wrong? Thank you in advance.

$Slmgr = cscript.exe C:\Windows\system32\slmgr.vbs /dlv

switch -Regex ($slmgr | Out-String){'(?s)ESU.+Activation ID: (.+?)(?=\r?\n)'{

[PSCustomObject]@{

ActivationID = $Matches[1]
    }
  }
}

UPDATE: This is the result of slmgr /dlv below. It was grabbing the first instance of the Activation ID from the OS Key, but now it's grabbing the correct key from ESU section using (?s)ESU.+?Activation ID:\s*([^\r\n]+) below in the comments.

http://imgur.com/gallery/BIJcyqM

But, the output is showing "Name", and "Value", where is I just need the # that is obfuscated alone to process it later.

http://imgur.com/gallery/gVPMeHM

Update

Apparently, on certain systems $Slmgr is an array, not a multiline string, so -match doesn’t work for a multiline regex.

I tried this, but it give me a bunch of additional info after the Activation key:

$Slmgr = cscript.exe C:\Windows\system32\slmgr.vbs /dlv
$Slmgr -match '(?s)ESU.+?Activation ID:\s*([^\r\n]+)'
$Slmgr -join "'r'n" -match '(?s)ESU.+?Activation ID:\s*([^\r\n]+)'
$ActivationID = $matches[1]

Looking at $ActivationID, it does have the Activation key in the beginning, then is shows “ ‘r ‘n “ that I have in my code, then a bunch of stuff after it as well like installation keys, certificate info. I think that my –join in my code is throwing something off.

Any ideas what I’m doing wrong or a better way of what I’m trying to accomplish?

1 Answers

You can do that using

$slmgr = cscript.exe C:\Windows\system32\slmgr.vbs /dlv
$ActivationID = If ($slmgr -match '(?s)ESU.+?Activation ID:\s*([^\r\n]+)') {$matches[1]} Else {""}

The (?s)ESU.+?Activation ID:\s*([^\r\n]+) regex matches

  • (?s) - RegexOptions.Singleline option on to make . match newlines, too
  • ESU - an ESU substring
  • .+? - one or more chars, as few as possible
  • Activation ID: - a literal phrase
  • \s* - zero or more whitespaces
  • ([^\r\n]+) - Capturing group 1: any one or more chars other than CR and LF.

Regarding the update, if your input is an array and you need to convert it to a string you need:

$slmgr = cscript.exe C:\Windows\system32\slmgr.vbs /dlv
$slmgrString = $slmgr -join "`r`n"
$ActivationID = If ($slmgrString -match '(?s)ESU.+?Activation ID:\s*([^\r\n]+)') {$matches[1]} Else {""}
Related