Hello,
I’ve written an advanced function that creates one or more VMs. I have a mandatory parameter and many optional, with some default values.
The problem is with the optional parameters that have no default values.
For example, there is a SwitchName parameter that is optional and has no default value, because I don’t always want a new VM to connect to a switch.
However, if I don’t supply any value to it, I get this error, even if I use [AllowEmptyString()] and [AllowNull()] in the PARAM block:
New-VM : Cannot validate argument on parameter 'SwitchName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
I want the VMs to connect to a switch only if I supply the name of a switch, otherwise I don’t want them to connect anywhere. How can I do this?
These are the relevant snippets from my code (sorry for the formatting, it gets messed up whatever I do):
#Some of the parameters:
[CmdletBinding()]
param(
[Parameter(Mandatory,
ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[string[]]
$VMName,
[Parameter(ValueFromPipeline,
ValueFromPipelineByPropertyName)]
[AllowEmptyString()]
[AllowNull()]
[string]
$SwitchName,
#And so on
)
PROCESS
{
foreach ($name in $VMName)
{
$params = @{Name = $name
MemoryStartupBytes = $MemoryStartupBytes
Generation = 2
NewVHDPath = "$VHDFolder\$name\$name.vhdx"
NewVHDSizeBytes = $VHDSizeBytes
BootDevice = $BootDevice
ComputerName = $ComputerName
Path = $VMFolder
SwitchName = $SwitchName}
New-VM @params
$params = @{VMName = $name
DynamicMemoryEnabled = $true
MinimumBytes = $MemoryMinimumBytes
ComputerName = $ComputerName}
Set-VMMemory @params
}
}