user3495534
user3495534

Reputation: 11

Parsing Strings in Powershell

I'm a c-shell guy so I am trying to learn powershell. I have the following file:

Environment: production

Servers : 3

Users : 25

Nodes : 20

Environment: alpha

Servers : 4

Users : 21

Nodes : 19

etc.

I want to check that if the first value on the left is "Environment" then I store in a variable the value on the right - "Production", then from there store each subsequent left/right pair until I hit the next "Environment" where I would store the next value.

I cannot make my regexp powershell work using ForEach-Object.

Upvotes: 0

Views: 291

Answers (2)

mjolinor
mjolinor

Reputation: 68341

Another possibility, since it seems to be well formatted data:

(@'
Environment: production
Servers : 3
Users : 25
Nodes : 20
Environment: alpha
Servers : 4
Users : 21
Nodes : 19
'@).split("`n") |
foreach {$_.trim()} |
set-content test.txt

get-content test.txt -ReadCount 4 |
foreach { 
 new-object psobject -property (convertfrom-stringdata ($_.replace(':','=') -join "`n"))
 } | ft -auto


Environment Users Nodes Servers
----------- ----- ----- -------
production  25    20    3      
alpha       21    19    4 

Upvotes: 0

Cole9350
Cole9350

Reputation: 5570

You shouldn't need regular expressions for this...

$servs = @()
get-content file.txt | % {
  $split = $_ -split ":"
  if($split[0].trim() -eq "Environment"){
     $obj = New-Object System.Object
     $obj | Add-Member -type NoteProperty -name $split[0] -value $split[1].trim()
  }
  elseif($split[0].trim() -eq "Nodes"){
     $obj | Add-Member -type NoteProperty -name $split[0] -value $split[1].trim()
     $servs += $obj
  }
  elseif($split -ne $null){
     $obj | Add-Member -type NoteProperty -name $split[0] -value $split[1].trim()
  }
}

Now you should have an array of custom objects in $servs that looks like:

Environment                         Servers                             Users                               Nodes                             
-----------                         --------                            ------                              ------                            
production                          3                                   25                                  20                                
alpha                               4                                   21                                  19

Upvotes: 1

Related Questions