Powershell - extract first and third element from string variable
Solution 1
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
Solution 2
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]
Admin
Updated on June 05, 2022Comments
-
Admin almost 2 years
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?