Hey everyone! I'm working with a PowerShell script that connects to a Cisco switch using `plink.exe`. The script grabs the output of `show int status` and places it into an array, but I'm having trouble with how the data is structured. The first few elements of the array are empty, and the actual data starts further down. I would like the resulting array to have clearly defined headers—specifically Port, Name, Status, VLAN, Duplex, Speed, and Type—so that I can access the data with commands like `$results.'Port'` and `$results.'Status'`. Right now, I can only get all the data as one long string for each entry. Any suggestions on how to parse and structure this correctly? Thanks!
5 Answers
It sounds like you need to parse the array since `plink.exe` returns plain strings instead of structured objects. You can loop through your results and split each line. Here's a sample you might find helpful:
```powershell
$parsedResults = foreach ($line in $results) {
if ($line -match '^Gi') { // Only grab lines starting with 'Gi'
$port, $name, $status, $vlan, $duplex, $speed, $type = $line -split 's+'
[PSCustomObject]@{
Port = $port
Name = $name
Status = $status
VLAN = $vlan
Duplex = $duplex
Speed = $speed
Type = $type
}
}
}
```
This should let you work with the parsed data like you wanted. Just be cautious; if the format changes even slightly, you'll need to adjust your parsing accordingly.
This is exactly what I was going for! Thanks a lot!
Does your switch support outputting data in different formats like XML or JSON? If so, that could make your life a lot easier to parse.
That's a good idea! I'll look into that option.
Check out `ConvertFrom-String`, too. It can simplify a lot of your parsing work automatically.
Glad you've got it sorted! Just a tip: you might prefer using the `OpenSSH` client in Windows instead of `plink`, especially with newer Windows versions. It offers a more seamless experience.
I've used Posh-SSH for automating SSH connections. It could be more user-friendly than the built-in client. Here's the link if you're interested: [Posh-SSH GitHub](https://github.com/darkoperator/Posh-SSH).
Could you share your existing code? I have a feeling you might need to create custom PSObjects to get the output formatted correctly.
Thanks for the input! Someone already guided me in the right direction.
Great advice! You could also use a `switch` statement to streamline this process further. Just make sure to match only the lines you want to parse.