Some background: I work in a laboratory environment and have a number of problems that arise that require the creation of VHD and attachment to virtual machines for stress testing. I came up with a script that allows the user to make the process as simple as possible, which is as follows:
$vms=Get-VM
$val = 0
Write-Host "This script is set up for quickly creating and initilizing VHDs"
$Path = Read-Host "Please enter the path you want to create the drives to. Use the formate in this example <E:\VHDS\>"
$fileName = Read-Host "The Drive will be <target>-<number>.vhdx. Please Name the target "
$vhdSize = 1GB
$vmAmount = Read-Host "How many Drives should be attached to each VM?"
foreach ($vm in $vms)
{
$n = $vm.Name
while ($val -ne $vmAmount)
{
$vhdPath = ($Path + $fileName + '-' + $val + '.vhdx')
New-VHD -Path $vhdPath -SizeBytes $vhdSize -Fixed | Mount-VHD -Passthru | Initialize-Disk -Passthru | New-Partition -AssignDriveLetter -UseMaximumSize | Format-Volume -FileSystem NTFS -Confirm:$false -Force | Dismount-VHD -Passthru
Add-VMHardDiskDrive -VMName $n -Path $vhdPath
$val++
}
}
When I run the code, it gives me a message stating that Dismount-VHD will not work with the specified path. I try to log in and give it the $ vhdPath variable, and it is still blocked.
Another problem that I am facing is that the while statement does not increment $ val. When it moves to the next statement, it displays an error message and stops, saying that the virtual machine already has a disk attached to it.
.