I am trying to find the number of partitions on a VHD of Hyper-V 2012 through a script. Currently I am doing this using a VBScript and a PowerShell script. For this I am first using a WMI query to find out the disk number (of the VHD) in the VBScript and passing this disk number as an argument to the PowerShell script, which gives the number of partitions.
Here are my questions:
Is there any direct way to find the attached VHD's number of partitions through script? If yes, please share.
The approach I am using in VBScript to find the disk number gives me different disk number of vhd every time depending on the disks attached (physical hard drive, VHD, backup disk, USB) to system in order. This could be wrong some time. Please tell me how to find out the disk number of specified VHD attached to the system.
Code in VBScript to find out the disk number:
strComputer = "."
Dim i
i = 0
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colQuotas = objWMIService.ExecQuery _
("Select * from Win32_DiskQuota")
For each objQuota in colQuotas
i= i+1
Next
i = i - 1
Wscript.Echo i
PowerShell script code:
$DN = $args[0]
Write-Host "disk number $DN"
$ObjPartition = Get-Partition -DiskNumber DN | measure
$NoOfPartition = $ObjPartition.count
Write-Host "No of Partition $NoOfPartition"
You could automate
diskpart
in PowerShell to determine the disk IDs and paths, and then use the IDs in a WMI query to determine the partition number. Example: