Catch errors when creating a VM using Powershell

Lger-3439 166 Reputation points
2023-05-21T16:20:13.8666667+00:00

When creating a new VM with Powershell, is there any way to catch errors?

New-VM -Name $vmname `
 -MemoryStartupBytes $memorySize `
 -Path D:\Hyper-V\ `
 -NewVHDPath D:\Hyper-V\$vmname\$vmname.vhdx `
 -NewVHDSizeBytes $diskSize `
 -Generation 2 `
 -SwitchName "vSwitch"

For example, an error can occur if the virtual switch does not exist. In this case, no more tasks should be processed and the script should be terminated.

System Center Virtual Machine Manager
Windows for business | Windows Client for IT Pros | Storage high availability | Virtualization and Hyper-V
Windows for business | Windows Server | User experience | PowerShell
Windows for business | Windows Server | User experience | Other
0 comments No comments
{count} votes

Answer accepted by question author
  1. Rich Matheisen 48,036 Reputation points
    2023-05-21T18:12:34.1833333+00:00

    The New-VM cmdlet recognizes all "Common-Parameters", so adding "-ErrorAction STOP" to the cmdlets' parameters and wrapping the cmdlet in a Try/Catch will allow you trigger a terminating exception for an errors encountered during the cmdlets' execution.

    Try{
        New-VM  -Name $vmname 
                -MemoryStartupBytes $memorySize 
                -Path D:\Hyper-V\ 
                -NewVHDPath D:\Hyper-V\$vmname\$vmname.vhdx 
                -NewVHDSizeBytes $diskSize 
                -Generation 2 
                -SwitchName "vSwitch"
                -ErrorAction STOP
    }
    Catch{
        # Report or handle the error here
    }
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.