Created
September 4, 2018 20:59
-
-
Save daBONDi/44262be144b0f4f8d56a12943bd2921c to your computer and use it in GitHub Desktop.
Powershell Class for Serial Communication with Network Switches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$comPort = "COM5" | |
class SerialCommunicator | |
{ | |
hidden [int] $WaitTimeForResponse=1 # Wait Time for Response in Seconds | |
hidden [int] $ComPortBaudRate=9600; | |
hidden [System.IO.Ports.Parity] $ComPortParity = [System.IO.Ports.Parity]::None; | |
hidden [int] $ComPortDataBits=8; | |
hidden [int] $ComPortStopBits=1; | |
hidden static [int] $ReadLineReadTimeout = 100 | |
# Public Propertys | |
hidden [string]$ComPortName | |
hidden [System.IO.Ports.SerialPort]$ComPort; | |
SerialCommunicator([String]$ComPort) | |
{ | |
$this.ComPortName = $ComPort; | |
$this.ComPort = New-Object System.IO.Ports.SerialPort $this.ComPortName,$this.ComPortBaudRate,$this.ComPortParity,$this.ComPortDataBits,$this.ComPortStopBits; | |
$this.ComPort.ReadTimeout = $this.ReadLineReadTimeout; | |
} | |
SendCommandAndWaitFor($Command,$RegEx) | |
{ | |
$this.ComPort.WriteLine($Command); | |
$this.WaitForLine($RegEx) | Out-Null; | |
} | |
[bool]WaitForLine([string]$RegEx) | |
{ | |
Start-Sleep -Seconds 1; | |
if($this.ComPort.BytesToRead) | |
{ | |
$data = $this.ComPort.ReadExisting(); | |
Write-Host $data; | |
if($data -match $RegEx) | |
{ | |
return $true | |
} | |
} | |
return $false; | |
} | |
[bool] OpenConnection() | |
{ | |
$this.ComPort.Open(); | |
if($this.ComPort.IsOpen){ | |
return $true; | |
}else{ | |
Write-Error "Error on Opening Comport" -ErrorAction Stop; | |
} | |
return $false; | |
} | |
[bool] CloseConnection() | |
{ | |
if($this.ComPort.IsOpen) | |
{ | |
$this.ComPort.Close(); | |
} | |
return $true; | |
} | |
} | |
$commandPrompt = "Procurve Switch 2510G-24#"; | |
$Switch = [SerialCommunicator]::new($comPort); | |
$Switch.OpenConnection(); | |
$Switch.WaitForLine("Press any key to continue") | |
$Switch.SendCommandAndWaitFor("$([char]13)",$commandPrompt) | |
$Switch.SendCommandAndWaitFor("show vlans", $commandPrompt); | |
$Switch.SendCommandAndWaitFor("show interfaces 1", $commandPrompt); | |
$Switch.CloseConnection(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment