Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting specific data from a string with regex and Powershell

Tags:

I want to extract from this string

blocked-process-report process id="process435d948" taskpriority="0" logused="0" waitresource="RID: 7:1:1132932:0" waittime= "3962166" ownerId="4641198" transactionname="SELECT" lasttranstarted="2011-09-13T17:21:54.950" XDES="0x80c5f060" lockMode="S" schedulerid="4" kpid="18444" status="susp ended" spid="58" sbid="0" ecid="0"

The value that is in bold, but only the value or 58. And this value can be with different values, sometimes 80 or 1000, etc. but always > 50.

How can I do this using regex and posh?

like image 932
user353401 Avatar asked Sep 13 '11 22:09

user353401


People also ask

How do I extract part of a string in PowerShell?

When you want to extract a part of a string in PowerShell we can use the Substring() method. This method allows us to specify the start and length of the substring that we want to extract from a string.

Can you use regex in PowerShell?

Powershell: The many ways to use regex The regex language is a powerful shorthand for describing patterns. Powershell makes use of regular expressions in several ways. Sometimes it is easy to forget that these commands are using regex becuase it is so tightly integrated.


2 Answers

The quick and dirty:

$found = $string -match '.*spid="(\d+)".*'
if ($found) {
    $spid = $matches[1]
}

where $string is your above mentioned string. This would match any string that has spid="somenumberhere", and make the number into a matched group, which you can extract using $matches[1].

like image 74
Jon Angliss Avatar answered Oct 07 '22 19:10

Jon Angliss


Save that as, say $string.

Then do

$string -match 'spid="(\d+)"'

If there is a match, the value you want will be in $matches[1]

like image 31
manojlds Avatar answered Oct 07 '22 20:10

manojlds