How to find number of partition of a virtual hard disk through script?

2.3k views Asked by At

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:

  1. Is there any direct way to find the attached VHD's number of partitions through script? If yes, please share.

  2. 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"
1

There are 1 answers

4
Ansgar Wiechers On BEST ANSWER

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:

('list vdisk' | diskpart) -match '\.vhd' | % {
  $a = $_.Trim() -split '  +', 5
  New-Object -Type PSObject -Property @{
    'ID'   = $a[1] -replace 'Disk '
    'Path' = $a[4]
  }
} | % {
  $flt = "DeviceID='\\\\.\\PHYSICALDRIVE$($_.ID)'"
  $partitions = gwmi Win32_DiskDrive -Filter $flt | select -Expand Partitions

  "{0}`t{1}`t{2}" -f $_.ID, $partitions, $_.Path
}