Home > Mobile >  Detect drive letter change and re-assign it (usb drive letter) in Windows 10
Detect drive letter change and re-assign it (usb drive letter) in Windows 10

Time:01-14

every now and then Windows (10) will swap the assigned drive letters of my 2 attached usb type 3 devices. So instead of having J: with a label "keedrive" and V: with a label "secondary", Windows will sometimes swap them, J: becomes "secondary" and V: "keedrive". I'm trying to have a Batch script that will check if the drives letter have changed and if so reset them as they were.

Currently, i have to manually re-assign the letters with Diskpart utility.

I have read about How to run a PowerShell script from a batch file and How do I capture the output into a variable from an external process in PowerShell, trying to get a working script. So far i bogged at the level of getting the output of a PowerShell command into a variable, not knowing how to set the condition for checking the drive letters based on the DeviceID and subsequently re-assign the letters accordingly. Please help. In advance thank you.

Here is the PowerShell commands i came up with

Get-CimInstance -ClassName CIM_StorageVolume | Format-Table -Property DeviceID, DriveLetter, Label | Tee-Object -variable UsBDrvLetters

CodePudding user response:

$Drive = Get-CimInstance -ClassName Win32_Volume -Filter "DeviceID = '<YourDeviceID>'"
$Drive | Set-CimInstance -Property @{DriveLetter ='<DesiredLetter>:'}

First command returns the CimInstance object and the second one pipes it to the set-CimInstance.

More to read about this topic:

https://devblogs.microsoft.com/powershell-community/changing-drive-letters-and-labels-via-powershell/

CodePudding user response:

I finally get the script working, albeit using another property (SerialNumber) of the Win32_Volume Class for the filtering.

$Drive = Get-CimInstance -ClassName Win32_Volume -Filter 'SerialNumber like "6316615927"'

$Drive | Set-CimInstance -Property @{DriveLetter ='G:'}

The filtering also works with the "Label" property.

Im still curious/confused as to why i can't filter with the "DeviceID" property; so i will be very very happy to see a solution for that.

Thank you.

  • Related