Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

PowerShell knows about your USB devices

2011-03-02

One of many things you can do with the Management assembly is to get the USB devices that is currently connected to your computer. To load the Management assembly, use this line of code (no line break here):

[System.Reflection.Assembly]::Load("System.Management, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

The class you want to create an instance from is called ManagementClass, and to its constructor you pass the management path that you want to use. USB devices are located in the Win32_USBHub path, so that is the argument that I pass to the constructor.

$Man = New-Object System.Management.ManagementClass("Win32_USBHub")

The GetInstances function returns a collection of objects, each object representing a device that actually is connected. Just for being crazy, I will make my target variable type safe.

[System.Management.ManagementObjectCollection]$Devs = $Man.GetInstances()

Now I can use ForEach-Obect cmdlet to iterate through the collection. For each device, I will write out the name of the device, the system ID and a blank line.

$Devs | ForEach-Object {
	Write-Output $_.GetPropertyValue("Name").ToString()
	Write-Output $_.GetPropertyValue("DeviceID").ToString()
	Write-Output ""
}

Finally, I have to free the resouces I have used.

$Devs.Dispose()
$Man.Dispose()

When you run this code, you should see a list of devices that is registered as connected to your machine, including the USB hubs. If you connect a device and run the script again, that device will show up in the list. With this code as base, you could easily write programs that detects changes to the list. That is, programs that detects when a new device is added or removed. The last item should be the device you inserted while your computer was running, and the first items are the devices that were available at system startup.

Categories: PowerShell

Tags: USB

Leave a Reply

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



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips