"System.Int64". Error: "Input string was not in a correct format

"System.Int64". Error: "Input string was not in a correct format

我使用 XML 文件来存储创建虚拟机的配置。我的 Powershell 脚本创建了虚拟机,但我在尝试将 MemoryStartup 值传递给 new-vm 函数时遇到此错误。

我试图通过在我的变量前指定 [int64] 来解决这个问题,但没有成功。我可以从 XML 文件中读取数据,但它把它看作一个字符串,函数要求它是一个 int64。

在我的 xml 文件中,我输入了: 4096MB

在我的 powershell 脚本中:

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

错误:

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

我似乎找不到在 Powershell 中执行此类转换的任何明确方法,因为它似乎使用本机隐式函数将内存值转换为整数。但是,通过尝试数字运算进行 隐式 转换似乎可以解决问题:

"512MB"/1
536870912

因此:

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

中有 很多 与您的问题相关的更多详细信息。请跳到那里给更好的来源投票。

找到解决方案:

XML 文件: 4GB

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

通过使用 Invoke-Expression 它就像一个魅力