Catch errors when creating a VM using Powershell

Lger-3439 161 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.

Windows Server 2019
Windows Server 2019
A Microsoft server operating system that supports enterprise-level management updated to data storage.
3,472 questions
System Center Virtual Machine Manager
Hyper-V
Hyper-V
A Windows technology providing a hypervisor-based virtualization solution enabling customers to consolidate workloads onto a single server.
2,550 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,382 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,096 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