'Powershell script to initialize new drives, naming them from array

I drummed up the following code to initialize new disks that are added to a Windows VM:

 $newdisk = get-disk | where partitionstyle -eq 'raw'

foreach ($d in $newdisk){
$disknum = $d.Number
$dl = get-Disk $d.Number | Initialize-Disk -PartitionStyle GPT -PassThru | New-Partition -AssignDriveLetter -UseMaximumSize
Format-Volume -driveletter $dl.Driveletter -FileSystem NTFS -NewFileSystemLabel "Disk $disknum" -Confirm:$false
}

Instead of using the disk number for the file system label, I want to use some predefined volume names, like "OS", "Data", "System", etc....

I tried $name = "OS", "Data", "System" and put that variable in place of $disknum, but that just added the whole string as the volume name as it looped through.

Am I missing something? Should it be a variable inside of the loop? How can I get it to read each name from the variable for each run of the disk initilization inside the loop ?

I am newish to powershell and seeing examples helps me quite a bit.



Solution 1:[1]

  1. you can initialize disk based on the size of the attached disk.
  2. In a scenario when you attach so many disks, you may want to attribute a specific letter to a disk based on it's size. #in this scenario, we will attribute letter F to a 20GB disk.
$disknum = @(get-disk | Where-Object partitionstyle -eq 'raw'| Where-Object {$_.Size /1GB -match '20'})
$dl = get-Disk $disknum.Number | 
Initialize-Disk -PartitionStyle GPT -PassThru | New-Partition -AssignDriveLetter -UseMaximumSize
Format-Volume -driveletter F -FileSystem NTFS -NewFileSystemLabel 'DB Data' -Confirm:$false

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 rivolity