2015年7月29日 星期三

Powershell下分析Diskpart.exe輸出資料

參考資料:



不同語系(locale) 的Diskpart.exe的輸出格式會有些許不同,下面Code是我在Windows 8.1中文版試過可行的,若要英文版請參考上面連結

Function GET-DISKPARTINFO() 
{ 
[cmdletbinding] 
# Build Script for LIST DISK in DISKPART 
 
New-item -Name listdisk.txt -Itemtype file -force | out-null 
add-content -path listdisk.txt "list disk" 
$listdisk=(diskpart /s listdisk.txt) 

# Get Total Disks outputted.   
# Yes.  It's as simple as "Count the lines on the screen" 
 
$totaldisk=$listdisk.count-8 

# Step through each line that will contain disk information 
for ($d=0;$d -lt $totaldisk;$d++) 
{ 
# Pull the Partition size data and the DiskNumber 
 
$size=$listdisk[8+$d].substring(25,9).replace(" ","") 
$diskid=$listdisk[8+$d].substring(5,5).trim() 

# Create a script to pull detail on the existing disk 
 
new-item -Name detail.txt -ItemType file -force | out-null 
add-content -Path detail.txt "select disk $diskid" 
add-content -Path detail.txt "detail disk" 
 
# Capture the output from Diskpart for the Detail 
 
$Detail=(diskpart /s detail.txt) 

# Parse the data for the partition 
 
$Model=$detail[8] 
$type=$detail[10].substring(9) 
$DriveLetter=$detail[-1].substring(12,1) #(15,1)

# Grab the partition sizing data 
 
$length=$size.length 
$multiplier=$size.substring($length-2,2) 
$intsize=$size.substring(0,$length-2) 
 
# Convert the Partition "KB/MB/GB" to a real value 
switch($multiplier) 
    { 
        KB { $mult=1KB } 
        MB { $mult=1MB } 
        GB { $mult=1GB } 
    } 
 
# Calculate the size of the Disk or Partition 
$disktotal=([convert]::ToInt16($intsize,10))*$mult 
  
# Return the Object back to the real world Neo 
[pscustomobject]@{DiskNum=$diskid;Model=$model;Type=$type;DiskSize=$disktotal;DriveLetter=$DriveLetter} 
} 
} 

輸出:
DiskNum     : 0
Model       : VMware, VMware Virtual S SCSI Disk Device
Type        :  SAS
DiskSize    : 64424509440
DriveLetter : C

DiskNum     : 1
Model       : USB FLASH DRIVE USB Device
Type        :  USB
DiskSize    : 4009754624
DriveLetter : E