PowerShell: Serial Port

Get available serial port

PS C:\> [System.IO.Ports.SerialPort]::GetPortNames()
COM7

Setup the port

PS C:\> $port = New-Object System.IO.Ports.SerialPort COM7,38400,None,8,one

PS C:\> $port

BaseStream             :
BaudRate               : 38400
BreakState             :
BytesToWrite           :
BytesToRead            :
CDHolding              :
CtsHolding             :
DataBits               : 8
DiscardNull            : False
DsrHolding             :
DtrEnable              : False
Encoding               : System.Text.ASCIIEncoding
Handshake              : None
IsOpen                 : False
NewLine                :

Parity                 : None
ParityReplace          : 63
PortName               : COM7
ReadBufferSize         : 4096
ReadTimeout            : -1
ReceivedBytesThreshold : 1
RtsEnable              : False
StopBits               : One
WriteBufferSize        : 2048
WriteTimeout           : -1
Site                   :
Container              :

Set port property

PS C:\> $port.DtrEnable = [bool]"true"
PS C:\> $port.NewLine = [byte]"0x1a"

PS C:\> $port

BaseStream             :
BaudRate               : 38400
BreakState             :
BytesToWrite           :
BytesToRead            :
CDHolding              :
CtsHolding             :
DataBits               : 8
DiscardNull            : False
DsrHolding             :
DtrEnable              : True
Encoding               : System.Text.ASCIIEncoding
Handshake              : None
IsOpen                 : False
NewLine                : 26
Parity                 : None
ParityReplace          : 63
PortName               : COM7
ReadBufferSize         : 4096
ReadTimeout            : -1
ReceivedBytesThreshold : 1
RtsEnable              : False
StopBits               : One
WriteBufferSize        : 2048
WriteTimeout           : -1
Site                   :
Container              :

Construct the request

PS C:\> [byte[]] $request = 0x00, 0x02, 0x33, 0x00

Send request to the port

PS C:\> $port.Open()
PS C:\> $port.Write($request, 0, $request.Count)
PS C:\> $port.Close()

References:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *