0

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.

1
  • For this simple text format you don't really need regular expressions. Either do Import-Csv datafile.txt -Delimiter ':' -Header Key,Value or just split the lines on the : character. Commented May 1, 2014 at 0:28

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

A much simpler solution than what I was trying to divine. Works perfectly.
0

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.