Archive

Posts Tagged ‘Windows Server 2008 R2’

Modify disk layout in Windows using powershell

So I have been configuring the company Altiris server (I love that tool) with some new jobs.

One of the headaches of past times, for me anyway, has been the modification of the disk layout, e.g. cd-rom must have letter so, a random number of physical disks must be formatted etc.

This is the powershell solution that I ended up with:

#first we find and initialize physical disks with no partitions 
$drives = gwmi Win32_diskdrive
$scriptdisk = $Null
$script = $Null
foreach ($disk in $drives){
    if ($disk.Partitions -eq "0"){
        $drivenumber = $disk.DeviceID -replace '[\\\\\.\\physicaldrive]',''        
$script = @"
select disk $drivenumber
online disk noerr
attributes disk clear readonly noerr
create partition primary noerr
format quick
"@
}
$drivenumber = $Null
$scriptdisk += $script + "`n"
}
$scriptdisk | diskpart

#then we will move the CDRom drive to x:
(gwmi Win32_cdromdrive).drive | %{$a = mountvol $_ /l;mountvol $_ /d;$a = $a.Trim();mountvol x: $a}

#then we will assign letters and labels to physical drives
# thanks to powershell.com for this bit
#(http://powershell.com/cs/blogs/tips/archive/2009/01/15/enumerating-drive-letters.aspx)
$volumes = gwmi Win32_volume | where {$_.BootVolume -ne $True -and $_.SystemVolume -ne $True -and $_.DriveType -eq "3"}
$letters = 68..89 | ForEach-Object { ([char]$_)+":" }
$freeletters = $letters | Where-Object { 
  (New-Object System.IO.DriveInfo($_)).DriveType -eq 'NoRootDirectory'
}
foreach ($volume in $volumes){
    if ($volume.DriveLetter -eq $Null){
        mountvol $freeletters[0] $volume.DeviceID
    }
$freeletters = $letters | Where-Object { 
    (New-Object System.IO.DriveInfo($_)).DriveType -eq 'NoRootDirectory'
}
} 

The script has been tested in PSHv2 installed on Windows Server 2008 and in native Windows 2008 R2 PSH, but should also work on Windows Server 2003, if it does not then I have to redo the Altiris job 🙂 – Update 14-11-2009: As it turns out the above will not work under Windows server 2003 – the updated version can be found here

The script first gets all the physical disks which have no partitions. Then it creates a script for use with diskpart. Once all physical disks are formatted, driveletters are assigned. First we move the cd-rom drive to x: then we loop through all volumes which are not BootVolume (e.g. c:\) or SystemVolume (W2k8 R2 reserved system partition)

Throw some comments or input to improve. I am particularly interested in a way to do this using .NET, so I do not have to use diskpart.

%d bloggers like this: