Jump to content

_GetComPorts


funkey
 Share

Recommended Posts

Maybe someone of you can need this:

#include <Array.au3>

Local $aComPort = _GetComPorts()
_ArrayDisplay($aComPort)

Local $sComPort = _GetComPorts("com1")
If @error Then
MsgBox(16, "Error " & @error, "No matching COM port found.")
Else
ConsoleWrite($sComPort & @CRLF)
EndIf

; #FUNCTION# ====================================================================================================================
; Name...........: _GetComPorts
; Description ...: Lists all com ports and their names to a 2D array, or returns only the name of the given com port
; Syntax.........: _GetComPorts($sComPort = "")
; Parameters ....: $sComPort - Either "" (blank) for array or a string like "1" or "COM1"
; Return values .: Success - Either an array or a string (depends on $sComPort)
;                  Failure - -1, sets @error
;                  |1 - No matching COM port found.
; Author ........: funkey
; Date ..........: 2010, Nov 29th
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
Func _GetComPorts($sComPort = "")
Local $objWMIService = ObjGet("winmgmts:\\localhost\root\CIMV2")
Local $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_PnPEntity WHERE Name LIKE '%(COM%" & StringReplace($sComPort, "COM", "") & ")'", "WQL", 48)
Local $sRet = ""
For $objItem In $colItems
  $sRet &= $objItem.Name & @CR
Next
If $sRet = "" Then Return SetError(1, 0, "")
If $sComPort <> "" Then
  If Not StringInStr($sRet, $sComPort) Or Not StringIsInt(StringRight($sComPort, 1)) Then Return SetError(1, 0, "")
  $sRet = StringTrimRight($sRet, StringLen("COM" & StringReplace($sComPort, "COM", "")) + 4)
  Return $sRet
EndIf
Local $aTemp = StringSplit($sRet, @CR, 2)
Local $aRet[UBound($aTemp) - 1][2]
For $i = 0 To UBound($aTemp) - 2
  $aRet[$i][0] = StringTrimRight(StringTrimLeft($aTemp[$i], StringInStr($aTemp[$i], "(", 0, -1)), 1)
  $aRet[$i][1] = StringLeft($aTemp[$i], StringInStr($aTemp[$i], "(", 0, -1) - 2)
Next
Return $aRet
EndFunc   ;==>_GetComPorts

Programming today is a race between software engineers striving to
build bigger and better idiot-proof programs, and the Universe
trying to produce bigger and better idiots.
So far, the Universe is winning.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...