从驱动器号中获取磁盘序列号 [英] obtain disk serial number from drive letter
问题描述
我想获取与 Windows 卷的驱动器号相关联的序列号,如从 PowerShell Get-Disk cmdlet 返回的序列号.我正在努力寻找任何可以为我指明正确方向的东西.我可以看到人们已经设法通过从 vbscript 和 c# 调用的 WMI 查询在现场执行此操作,例如
I would like to get the serial number, as in the serial number returned from the PowerShell Get-Disk cmdlet, associated with the drive letter of a windows volume. I'm strugling to find anything that will point me in the correct direction for how to do this. I can see that people have managed to do this on site this via WMI queries invoked from vbscript and c#, e.g.
private string GetDiskIndex(string driveLetter)
{
driveLetter = driveLetter.TrimEnd('\\');
ManagementScope scope = new ManagementScope(@"\root\cimv2");
var drives = new ManagementObjectSearcher(scope, new ObjectQuery("select * from Win32_DiskDrive")).Get();
foreach(var drive in drives)
{
var partitions = new ManagementObjectSearcher(scope, new ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition")).Get();
foreach(var partition in partitions)
{
var logicalDisks = new ManagementObjectSearcher(scope, new ObjectQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition")).Get();
foreach (var logicalDisk in logicalDisks)
{
if (logicalDisk["DeviceId"].ToString() == driveLetter) return partition["DiskIndex"].ToString();
}
}
}
return null;
}
在 PowerShell 中是否有一种优雅的方法来执行此操作?
Is there an elegant way of doing this in PowerShell ?
推荐答案
WMI/CIM 的东西也可以用 powershell 来完成.但你也可以这样做:
The WMI/CIM stuff could be done with powershell too. But you can also do:
get-partition -DriveLetter C | get-disk
这篇关于从驱动器号中获取磁盘序列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!