'Possible to assign disk drive letter to unassigned drives depending on size via powershell
Currently spinning up 11 unallocated volumes via terraform but noticed that the volumes come in a random order on the machine and not in the specified order of the code. Trying to figure out a way to name and assign a drive letter dependent on the size of the disk via powershell
Solution 1:[1]
PLEASE NOTE: I did not test this code as I don't have a environment currently for that.
Nonetheless, this should accomplish what you want, but may need some tweaks if you prefer a different partition style or what not.
It gets all the disks that are not online then puts them online.
Then within a loop
- It uses MBR partition style on each disk
- creates a new partition using the full diskspace
- query the disk to show what size it is in GB
- Show the disk size then prompt for the designated drive letter from user input
- verify the drive letter is not being used and is a valid letter
- format the drive with the letter using NTFS
# get new ebs volumes applied from terraform
$newDisks = Get-Disk | Where-Object {$_.IsSystem -eq $False -and $_.PartitionStyle -eq "RAW"}
$usedLetters = (Get-Volume).DriveLetter
foreach ($disk in $newDisks){
# set disk to online
try {
Set-Disk -Number $disk.Number -IsOffline $False
}
catch {
throw "could not get disk online"
}
#? create partition change MBR to GBT if preferred
try {
Initialize-Disk -Number $disk.Number -PartitionStyle "MBR"
}
catch {
throw "initialization failed"
}
try {
$partition = New-Partition -DiskNumber $disk.Number -UseMaximumSize
}
catch {
throw "partition failed"
}
# get the size to know which letter should get assigned
$partSize = Get-Partition -PartitionNumber $partition.PartitionNumber
$partSize = [math]::round((($partSize.size)/1GB),2)
$size = "$partSize GB's"
# get drive letter from user
$driveLetter = Read-Host "Drive letter for disk that is $size"
$letters = @("b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")
# check if letter is valid
$isLetter = $null -ne ($letters | Where-Object {$driveLetter -ieq $_})
# check if letter is already used
if ($isLetter){
$isLetter = $null -eq ($usedLetters | Where-Object {$driveLetter -ieq $_})
}
if(!$isLetter) {
throw "invalid drive letter $driveletter"
}
# finally format the drive with the letter
try {
Format-Volume -DriveLetter $driveLetter -FileSystem NTFS -Confirm:$FALSE
}
catch {
throw "format failed"
}
}
Hope it helps, let me know if there are any issues and I can step through it. Also, there is possibility to run a similar script within terraform itself while launching the instance (user_data), but that takes a bit more leg work and might not be feasible if system is already running :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | marc_s |