问题
Some background: I work in a lab environment and have a number of issues that come through that require VHDs to be created and attached to VMs for stress testing. I have come up with a script that allows the user to make the process as simple as possible, which is the following:
$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 an error stating that Dismount-VHD will not work with the path given. I attempt to go in and give it the $vhdPath variable, and it still blocks out.
Another problem I'm running into is that the while statement is not incrementing $val. When it goes into the next statement, it throws an error and stops, saying that the VM in question already has the disk attached to it.
Any help would be appreciated.
回答1:
I understand the beauty of pipelines in PowerShell, but this is going a little bit too far :). If you split the large pipeline, things work fine.
$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
The main problem with what you trying to do, is that Dismount-VHD does not accept pipeline input and even if it did, it would not know what to do with a volume object (this is the output of Format-Volume)
If you want to keep the pipeline, put Dismount-VHD -Path $vhdPath
on a separate line and all should be well.
Also when creating paths, you should use join-path to avoid issues.
回答2:
Only the dismount couldn't work on the pipeline.
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
I'm wondering if we could go even far.
来源:https://stackoverflow.com/questions/29836665/trying-to-create-initialize-and-format-vhd-disks