MDS
MDS

Reputation: 21

Powershell - extract first and third element from string variable

I have a variable called $Disk which is populated via a foreach loop that processes the output of a command that returns many lines of output.

For each iteration of the loop the $Disk variable contains data similar to:

Harddisk4  Disk1  SQLDG1  MBR   0     0   Offline     DISKS@SERVER1    P4C0T0L3 - -    F6799A78-9C10-443C-B4E6-22E3B30563C0 60003FFF409638B0B4E622E3B30563C0

I need to extract the first and third words from this string; all “words” in the string can be of variable length.

I would like to end up with:

$Harddisk equal to: Harddisk4

$DG equal to: SQLDG1

So far I have not found a way to do this. What options does powershell have to accomplish this?

Upvotes: 2

Views: 15575

Answers (4)

Silviu
Silviu

Reputation: 298

Because you wanted the values outputed into 2 variables it requires a bit of fiddling. The best I could do is:

$arr = $Disk -split "  "; $Harddisk=$arr[0]; $DG = $arr[2]

Upvotes: 1

Thanks Matt,

Here's what I ended up using for the Security Event-log events for account lock outs.

#Event Log Information
$EventInfo = Get-EventLog "Security" | Where {$30MinutesAgo -le $_.TimeWritten -and $_.eventid -eq 4740} | Format-List | Out-String 
ForEach ($line in $EventInfo){
    #Split line with ReplacementStrings : {accountname, computer, S-1..., S-1-5...} line
    $splitUp = $line -split "{"
    $EvReplacementStrings = $splitUp[1] -split ", "
    $EvUserName = $EvReplacementStrings[0]
    $EvComputer = $EvReplacementStrings[1]
}   

Upvotes: 0

Matt
Matt

Reputation: 46730

Marcus's answer is very elegnate using named matches

To show another approach, as there is always another

ForEach($line in $Document){
    $splitUp = $line -split "\s+"
    $Harddisk = $splitUp[0]
    $DG = $splitUp[2]
    ... other code stuff
}

or from pipeline

Get-Content c:\somefile.txt | ForEach-Object{
    $splitUp = $_ -split "\s+"
    $Harddisk = $splitUp[0]
    $DG = $splitUp[2]
    ... other code stuff
}

\s+ will split the line on any group of whitespace leaving you every single word. That might be any issue with some text but as long as the details you are looking for do not contain spaces it will suit. 0 and 2 would represent the 1st and 3rd entries in a base 0 array.

Would give the following output for $Harddisk and $DG.

Harddisk4
SQLDG1

Upvotes: 3

Marcus
Marcus

Reputation: 6117

One way to accomplish this is to use a regular expression to process each line, depending on what your exact input format is, it could look something like this:

foreach($Disk in (Get-ManyLinesOfOutput)) {
   if ($Disk -match "^(?<harddisk>\S+) \w+ (?<dg>\S+)") {
       $Harddisk = $matches["harddisk"];
       $DG = $matches["dg"];
       # do something
   }
}

For the .NET regular expression syntax used by PowerShell see e.g. http://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx.

Upvotes: 0

Related Questions