Home > Blockchain >  Setting the VirtualHardDiskPath when adding a virtual machine through powershell to Hyper-V
Setting the VirtualHardDiskPath when adding a virtual machine through powershell to Hyper-V

Time:11-05

I'm adding a vm through powershell to Hyper-V. The add is working but it's setting the config/xml files on the same drive as the vhdx file.

I am setting the $config and then running my new-vm.

$config= Get-VMHost | Select-Object VirtualMachinePath

I end up with this:

@{VirtualMachinePath=F:\vmconfigs}

This is how I'm adding the vm:

New-VM -Name $name -MemoryStartupBytes 8192MB -VirtualHardDiskPath $config -Path $driv\vm -Generation 2 -SwitchName (Get-VMSwitch).Name

If I run it without the -VirtualHardDiskPath, it places the configs in a folder on the same drive as the vhdx file. Of course, it will not run with the way it's set with the path added since it is not formatted correctly.

You can see here that my default is f:\vmconfigs but it's not using that folder when I manually add it.

VirtualHardDisk

So, I have two questions. First, how do I get the VirtualMachinePath correctly. Second, why isn't it putting the configs in the default folder (f:\vmconfigs) if I do not set it with powershell at the command line? If I add it through the interface, it is correct.

Thanks!

EDIT

This is what happens:

Folder

Even though the virtual machine path is f:\vmconfigs

My current command:

New-VM -Name $name -MemoryStartupBytes 8192MB -Path $driv\vm -Generation 2 -SwitchName (Get-VMSwitch).Name

CodePudding user response:

I wasn't using -path correctly. I ended up with this:

# ---------------- vhdx File Locations -----------------
# the main virtual machine to be added
$sysprep= "C:\SysPrep\sysprep2019.vhdx"
# the 'd: drive' that is to be added
$sysprep2= "C:\SysPrep\sysprep2019_2Drive.vhdx"

# ---------------- Hardware Settings -----------------
# number of processors to allocate
$numprocs= 6
# startup memory, defaults to 8gb
$startupmem= 8192MB

Write-Output "Creating the new virtual machine $name."
New-VM -Name $name -MemoryStartupBytes $startupmem -Generation 2 -SwitchName (Get-VMSwitch).Name

Write-Output "Adding $sysprep to the new virtual machine."
Add-VMHardDiskDrive -VMName $name -Path $newfile

if($secdrive -match 'y')
{
    Write-Output "Adding second drive to guest operating system."
    Add-VMHardDiskDrive -VMName $name -Path $newfile2
    Write-Output "$sysprep2 has been attached."
}

# set number of processors
Write-Output "Setting the number of processors to $numprocs"
Set-VMProcessor $name -Count $numprocs

Granted, this is only part of my script. So, I create the VM first in Hyper-V then add the drives to it.

  • Related