Reputation: 1235
Is there any way to catch an error when creating a new Hyper-V VM with Powershell?
New-VM -Name $vmname `
-MemoryStartupBytes $memorySize `
-Path D:\Hyper-V\ `
-NewVHDPath D:\Hyper-V\$vmname\$vmname.vhdx `
-NewVHDSizeBytes $diskSize `
-Generation 2 `
-SwitchName "vSwitch"
As far as I can see, there is no way to add -ErrorAction Stop to New-VM.
Errors can occur, for example, if the virtual switch does not exist. In this case no further tasks should be processed and the script should be terminated.
Upvotes: 1
Views: 411
Reputation: 9133
What you are saying is not error. You have to have a conditional check. I have given a rough skeleton for you to proceed along with error handling:
try ##runs everything in the try block to capture and error in the catch block
{
If(Get-VM -Name $vmname) ##checks if the VM is existing or not by fetching the VM information. It has further parameters. Kindly google about them for better understanding
{
"$vmname is already present"
}
else
{
## Only creates the VM when it doesnt exist
New-VM -Name $vmname `
-MemoryStartupBytes $memorySize `
-Path D:\Hyper-V\ `
-NewVHDPath D:\Hyper-V\$vmname\$vmname.vhdx `
-NewVHDSizeBytes $diskSize `
-Generation 2 `
-SwitchName "vSwitch"
}
}
catch
{
$_.Exception.Message ## Only captures the error exception message and not the entire error.
}
I have given explanations in the Comment block for you to understand it better.
Upvotes: 1