Splatting in script


I wrote a script that perfectly works without splatting, but it always breaks with splatting.
I don’t know what am I doing wrong, since I do it exactly as in a TechNet example.
Generation = “2” gets screwed up by the forum, not me :slight_smile:

    [Parameter(Mandatory = $true, ValueFromPipeline = $true)]

    [Parameter(Mandatory = $true)]

    [Parameter(Mandatory = $true)]

    foreach ($name in $VMName)
        $params = @{
            Name = "$name"
            MemoryStartupBytes = "1GB"
            Generation = "2"
            Path = "C:\Lab\VM"
            SwitchName = "$SwitchName"
        New-VM @params
        #the script completes perfectly with the line below, but breaks with splatting, becuse the VMs don't get created
        #New-VM -Name $name -MemoryStartupBytes 1GB -Generation 2 -Path C:\Lab\VM -SwitchName $SwitchName

        New-VHD -Path C:\Lab\VHD\$name\$name.vhdx -SizeBytes 40GB -Dynamic
        Set-VMMemory -VMName $name -DynamicMemoryEnabled $true -MinimumBytes 512MB
        Add-VMHardDiskDrive -VMName $name -Path C:\Lab\VHD\$name\$name.vhdx
        Add-VMDvdDrive -VMName $name -Path $ISOPath

        $network = Get-VMNetworkAdapter -VMName $name
        $vhd = Get-VMHardDiskDrive -VMName $name
        $dvd = Get-VMDvdDrive -VMName $name

        Set-VMFirmware -VMName $name -BootOrder $dvd,$network,$vhd

My first guess would be to remove the double quotes from your parameters that specify a variable.

I tried, didn’t help. I also tried with semicolons between the parameters, but got the same errors.
The VHD gets created alright, but not the VM. I’ve searched the internet for every possible way of splatting and the syntax should be correct.
I don’t know, maybe foreach doesn’t like splatting?

I’d mirror your parameters via splatting EXACTLY the same as the params that work. The double quotes aren’t being used in the method that’s working. Also, since you’re closing the Generation param in quotes, you’re typecasting that to a string. In your method that works, you’re passing an integer. Along the same lines, when you enclose 1GB in double quotes, that makes it a string while 1GB without quotes is an integer. I haven’t seen this be a problem because of Powershell’s weak typing but the New-VM cmdlet may be needing a specific datatype.

$params = @{
Name = $name;
MemoryStartupBytes = 1GB;
Generation = 2;
Path = “C:\Lab\VM”;
SwitchName = $SwitchName;

The problem was exactly what you said! Now it completes successfully! Thank you!

Awesome! Glad I could help.