1

I have a PS script that pulls some status information from a switch. The output looks like this:

     8    Auto       Unknown        -1  Class 4      On     Good      3.29       47.75        68.96

I now need to assign these strings to variables, for further processing. I'm guessing RegEx would be the best (only?) way to do it, but I don't have the first clue on how to achieve that, so any suggestion will be gratefully received.

Cheers,

B.

2
  • Is output object or plaint text? Commented Apr 7, 2020 at 11:27
  • The text is stream return from an SSH command. The stream is assigned to a variable, which I ran through a write-host, just to create the sample when asking the question. Commented Apr 7, 2020 at 11:38

1 Answer 1

2

Since the fields seem to be separated by varying numbers of spaces, it is simplest to use the unary form of -split, the string splitting operator:

# Sample input.
$line = @'
     8    Auto       Unknown        -1  Class 4      On     Good      3.29       47.75        68.96
'@

# Split the line into an array of fields by whitespace.
$fields = -split $line

# Output the result.
$fields

If you additionally want to infer the data types of the fields, simply by seeing if they can be converted to an integer ([int]) or a floating-point value ([double]):

foreach ($i in 0..($fields.Count-1)) {
  if ($newValue = $fields[$i] -as [double]) { $fields[$i] = $newValue }
  if ($newValue = $fields[$i] -as [int])    { $fields[$i] = $newValue }
}

Sign up to request clarification or add additional context in comments.

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.