Trying to create. initialize and format VHD drives

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.

.

+4
2

PowerShell, :). , .

    $vhdPath = (Join-path $Path  ($fileName + '-' + $val + '.vhdx'))
    New-VHD -Path $vhdPath -SizeBytes $vhdSize -Fixed 
    Mount-VHD -Path $vhdPath
    $disk = get-vhd -path $vhdPath
    Initialize-Disk $disk.DiskNumber
    $partition = New-Partition -AssignDriveLetter -UseMaximumSize -DiskNumber $disk.DiskNumber
    $volume = Format-Volume -FileSystem NTFS -Confirm:$false -Force -Partition $partition
    Dismount-VHD -Path $vhdPath
    Add-VMHardDiskDrive -VMName $n -Path $vhdPath 

, , , Dismount-VHD , , , ( -)

, Dismount-VHD -Path $vhdPath , .

join-path, .

+4

.

New-VHD -Path $image -SizeBytes $size |
    Mount-VHD -Passthru |
    Initialize-Disk -PassThru |     
    New-Partition -AssignDriveLetter -UseMaximumSize | 
    Format-Volume -FileSystem NTFS -Confirm:$false -Force
Dismount-VHD -Path $vhdPath
Get-VM -Id $vm | 
    Get-VMScsiController | 
    Add-VMHardDiskDrive -Path $image

, .

0

Source: https://habr.com/ru/post/1584378/


All Articles