如何获取当前工作分区所属硬盘的序列号?
Got it, let's solve this exactly how you need it—you want to pull the serial number of the physical drive that hosts your current working partition (not the other drive) using WMIC. Here's a straightforward, reliable approach tailored to your setup (C/D on one drive, E on another):
Step 1: Understand the WMI Relationship
Windows WMI has a built-in association class Win32_LogicalDiskToDiskDrive that links logical partitions (like C:, D:) to their parent physical hard drives. We'll use this to map your current working drive to its physical disk, then grab the serial number.
Step 2: One-Liner or Batch Script
Quick One-Liner (Run Directly in Command Prompt)
This command will automatically detect your current working drive, map it to the physical disk, and output the serial number:
for /f "skip=1 tokens=*" %%d in ('wmic logicaldisk where "DeviceID='%cd:~0,2%'" get DeviceID') do @for /f "tokens=2 delims==" %%a in ('wmic path win32_logicaldisktoDiskDrive where "Dependent='Win32_LogicalDisk.DeviceID=\"%%d\"'" get Antecedent /value') do @for /f "skip=1 tokens=*" %%s in ('wmic diskdrive where "DeviceID='%%a'" get SerialNumber') do @echo %%s
Clean Batch Script (Easier to Read/Modify)
If you want a cleaner output (no extra blank lines), save this as GetCurrentDriveSerial.bat and run it:
@echo off setlocal enabledelayedexpansion :: Extract current working drive (e.g., C: from C:\Users\...) set "currentDrive=%cd:~0,2%" :: Remove any trailing spaces from the drive identifier set "currentDrive=!currentDrive: =!" :: Map logical drive to physical disk via WMI association for /f "tokens=2 delims==" %%a in ('wmic path win32_logicaldisktoDiskDrive where "Dependent='Win32_LogicalDisk.DeviceID=\"!currentDrive!\"'" get Antecedent /value') do ( set "diskID=%%a" set "diskID=!diskID: =!" :: Fetch and clean the serial number for /f "skip=1 tokens=*" %%s in ('wmic diskdrive where "DeviceID='!diskID!'" get SerialNumber') do ( set "serial=%%s" set "serial=!serial: =!" echo Current Partition's Parent Drive Serial Number: !serial! ) ) endlocal
How It Works
%cd:~0,2%grabs the first two characters of your current working directory path, which gives you the drive letter (e.g.,C:).- The
Win32_LogicalDiskToDiskDrivequery finds the exact physical disk that hosts your current drive. - We clean up extra spaces and blank lines common in WMIC output to get a clean serial number you can use for your authorization code generation.
Test It Out
- If you run this while working in C: or D:, it will return the serial number of your first drive.
- If you switch to E: and run it, it will return the serial number of your second drive. Perfect for your use case!
内容的提问来源于stack exchange,提问作者Daril Alemán

