我正在尝试创建一个脚本,将驱动器号(即D:\或E:\ETC)与USB VID/PID(即“USB\VID_XXXX&PID_XXX\xxxxxxxxxxxxxx”)。我试着在整个互联网上搜索,但除了这里的:See accepted answer at the top之外,没有找到任何有希望的东西
这个答案能够解决这个问题,但我需要它在PowerShell中。我已经尝试将代码转换为PowerShell,但它不起作用,如果能提供任何帮助,我将不胜感激。
注意:您可以使用以下代码片段获取设备示例ID:
# Declaring variable & getting information about all the connected USB devices
$InstanceID = ""
$ConnectedDevices = Get-PnpDevice -Class "USB"
# Applying filter for USB Mass Storage Device and storing the instance ID to be used at later stage
ForEach($USB in $ConnectedDevices)
{
If ($USB.FriendlyName -contains "USB Mass Storage Device")
{
$InstanceID = $USB.DeviceID
}
}
以下是不起作用的代码(或者,您可以将失败的努力称为失败的代码):
$AllDevices = Get-CimInstance -ClassName Win32_USBHub
$InstanceID = "USB\VID_XXXX&PID_XXX\XXXXXXXXXXXXXXX"
$AllProperties
$USBObjects
$SecondIdentity
$AllDrives = Get-CimInstance -ClassName Win32_DiskDrive
Foreach($device in $AllDevices)
{
If($device.DeviceID -like $InstanceID)
{
$AllProperties = $device
}
}
Function FindPath
{
ForEach($DeviceProperty in $AllProperties)
{
If($Device.Description -Contains "*USB Mass Storage Device")
{
$Entity = $Device.DeviceID
ForEach($Controller in $Entity.GetRelated('Win32_USBController'))
{
$USBControllerID = gwmi win32_diskdrive | %{gwmi -Query "ASSOCIATORS OF {Win32_USBController.DeviceID='" + $Controller.DeviceID + "'} WHERE AssocClass = Win32_USBController"}
ForEach($Obj in $USBControllerID)
{
If($Obj -contains "Device ID")
{
$USBObjects = $Obj.DeviceID
$USBObjects
}
}
}
}
$VidPidPosition = $USBObjects.Indexof($Entity)
for($i = $VidPidPosition; $i -le $USBObjects.Count; $i++)
{
if($USBObjects.[i] -contains "USBSTOR")
{
$SecondIdentity = $USBObjects.[i]
}
}
}
}
Function GetDriveLetter
{
FindPath
ForEach($Drive in $AllDrives)
{
If($Drive.PNPDeviceID -eq $SecondIdentity)
{
ForEach($o in $Drive.GetRelated('Win32_DiskPartition'))
{
ForEach($i in $o.GetRelated('Win32_LogicalDisk'))
{
Write-Output "Disk: " $i.Name
}
}
}
}
}
GetDriveLetter
1条答案
按热度按时间vnjpjtjt1#
集思广益后,我可以找到一种更容易的方法来实现这一点,即将USB驱动器号与ID/VID相关联。如果您注意到,在字符串“USB\VID_XXXX&PID_XXXX\123X5678X0987X543210XXXX”,中,字符串后面跟着最后一个反斜杠,这与“usbstor”字符串中的情况相同,该字符串可用于比较两者。
下面是可用于从txt文件中读取驱动器号并将其与PID/VID进行比较的示例代码。最后,如果匹配,它将使用PNPUtil执行断开和重新连接