0

Good evening everybody,

I need help with a simple variable in Powershell. I'm trying to auto the creation of VM in Hyper-V trough Powershell.

I'm trying to prompt via Read-Host the amount of RAM GB but I received the same error all time.

$ram = Read-Host -Prompt "Ram to use"
New-VM -Name $vm -MemoryStartupBytes $ram -BootDevice VHD -NewVHDPath C:\HyperV\Virtualmachines\$vm.vhdx -Path C:\HyperV\Virtualmachines -NewVHDSizeBytes $disc1 -Generation 2 -Switch Data
New-VHD -Path C:\HyperV\virtualmachines\"$vm"_2.vhdx -SizeBytes 40GB -Dynamic

This is the error I received.

Two of them, one from the bytes and the other the correct format

New-VHD : Cannot bind parameter 'SizeBytes'. Cannot convert value "[60GB]" to type "System.UInt64". Error: "Input string was not in a correct format."

The minimum amount of memory you can assign to this virtual machine is '32' MB.

I dont understand why is not working with GB if a put myself the amount in the properly powershell work fine but if I write in the variable doesnt work

zett42
  • 25,437
  • 3
  • 35
  • 72
Frit0
  • 5
  • 3
  • Does this answer your question? [How to convert to UInt64 from a string in Powershell? String-to-number conversion](https://stackoverflow.com/questions/41088561/how-to-convert-to-uint64-from-a-string-in-powershell-string-to-number-conversio) – zett42 Mar 10 '22 at 15:56
  • So this should work: `-MemoryStartupBytes ([uint64] ($ram / 1))`. BTW, on PS 7+, your code already works without further ado, because PS 7+ implicitly converts strings with multiplier suffix into numeric value. – zett42 Mar 10 '22 at 15:58

1 Answers1

1

A user can type in anything in Read-Host..
To remove the fluff, do something like

$ram = Read-Host -Prompt "Ram to use (GB)"
$ram = [uint64]($ram -replace '\D') * 1GB  # now you have the value as UInt64
Theo
  • 57,719
  • 8
  • 24
  • 41