0

I use an XML file to store configuration for creating virtual machines. My Powershell script creates the VM but I get this error where I'm trying to pass the MemoryStartup value into the new-vm function.

I tried to fix this by specifying [int64] before my variable but no luck. I can read the data from the XML file but it sees it as a string and the function requires it to be an int64.

In my xml file I put: 4096MB

In my powershell script:

new-vm -ComputerName $Using:Hostname -name $Using:VMName -MemoryStartupBytes [int64]$Using:MemoryStartup

Error:

Cannot bind parameter 'MemoryStartupBytes'. Cannot convert value "[int64]4096MB" to type "System.Int64". Error: "Input string was not in a correct format."
    + CategoryInfo          : InvalidArgument: (:) [New-VM], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.HyperV.PowerShell.Commands.NewVM
Steve can help
  • 470
  • 7
  • 19
MDH98
  • 21
  • 2
  • 1
    [1] please read the Tour page for a link to how to format code ... and then format your code to make it easily read. [*grin*] ///// [2] why are you using `$Using:`? i don't see the need for it in your code. ///// [3] you need to make sure that the `[int64]4096MB` is getting converted to a number BEFORE trying to use it. you may need to wrap it in `()` to force it to be evaluated before it is used. – Lee_Dailey Jan 26 '22 at 06:01
  • Can't be reproduced with this information: `[Int64]([Xml]'4096MB').Test` works fine. – iRon Jan 26 '22 at 09:38
  • 1
    @iRon not in ps 5.1 – js2010 Jan 28 '22 at 01:34
  • @js2010, good point. Workaround: `[int64](0 + ([Xml]'4096MB').Test)` (or use [PowerShell Core](https://learn.microsoft.com/powershell/scripting/install/installing-powershell-on-windows)) – iRon Jan 28 '22 at 10:03

2 Answers2

1

I can't seem to find any explicit way to perform this type of casting in Powershell, as it appears to use native implicit functions to convert memory values to integers. However, an implicit cast by attempting a numeric operation seems to do the trick:

"512MB"/1
536870912

Therefore:

new-vm -ComputerName $Using:Hostname -name $Using:VMName -MemoryStartupBytes [int64]$($MemoryStartup/1)

There are lots more details relevant to your question in How to convert to UInt64 from a string in Powershell? String-to-number conversion. Do hop over there to give the superior source an upvote.

Steve can help
  • 470
  • 7
  • 19
0

Found a solution:

XML file: 4GB

Powershell file: new-vm -ComputerName $Hostname -name $VMName -MemoryStartupBytes (Invoke-Expression $MemoryStartup) -Generation 2 -Path $LocationPath

By using the Invoke-Expression it works like a charm

MDH98
  • 21
  • 2
  • That is a pretty expensive workaround. Besides it is recommended to avoid [`Invoke-Expression`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/invoke-expression#description) – iRon Jan 28 '22 at 10:05