1

我在编写创建新 VHD(用于创建网络优化包的工具)的脚本时遇到问题。下面的脚本基本上提取输入目录的总大小并将其作为变量传递给 $intval 函数,该函数将字节大小转换为字符串 $size (nGB)。

我遇到的问题是 cmdlet NEW-VHD 要求 -SizeBytes 参数采用 Uint64 格式。如果您手动输入参数,例如

NEW-VHD -path $vhdpath -fixed -SizeBytes 10GB

cmdlet 按预期运行并创建 VHD,因为它接受 10GB 作为 Uint64。我需要的是变量 $size 以某种方式转换为 Uint64,同时保留尾随 GB。在这种情况下有什么方法可以模仿用户输入吗?

我知道下面的脚本没有优化或最好看,因为它只是一个概念证明。欢迎对上述问题提出任何建议!

代码

$dir = Read-Host 'What is the directory you are wishing to store inside a VHD?'
$objFSO = New-Object -com Scripting.FileSystemObject
$intval = $objFSO.GetFolder($dir).Size / 1GB
$size = "{0:N0}GB" -f $intval
$vhd = Read-Host 'What volume name do you wish to call your VHD (no spaces)?'
$vhdname = ($vhd + ".vhdx")
$vhdpath = ("C:\VHD\" + $vhdname)
NEW-VHD -fixed -path $vhdpath -SizeBytes $size

我已经查看了一些 Microsoft 资源,但结果都是空的

修改后的代码

$dir = Read-Host 'What is the directory you are wishing to store inside a VHD?'
$objFSO = New-Object -com Scripting.FileSystemObject
$intval = $objFSO.GetFolder($dir).Size
$size = $intval / 1GB
$vhd = Read-Host 'What volume name do you wish to call your VHD (no spaces)?'
$vhdname = ($vhd + ".vhdx")
$vhdpath = ("C:\VHD\" + $vhdname)
NEW-VHD -fixed -path $vhdpath -SizeBytes $size
4

4 回答 4

3

只需使用这个:

$size = $intval / 1G

PowerShell 具有用于将值转换为千兆字节的内置常量 (GB)。也见这里

编辑:阅读您的评论,我似乎误解了您的问题。New-vhd 需要以字节为单位的大小。如果你想要 10 GB,你可以像这样转换值:

$size = [bigint] 10GB

您的问题不清楚的是:“我需要的是变量 $size 以某种方式转换为 Uint64,同时保留尾随 GB”。

于 2013-09-04T06:45:42.210 回答
2

这是我为了解决奇怪的小错误而编写的代码。

#-------------------------------VHD CREATION-------------------------------------#

#Create a VHD with a size of 3MB to get around variable bug
        New-VHD -Path $vhdpath -SizeBytes 3MB -Fixed
#Resize to target dir + extra
        Resize-VHD -Path $vhdpath -SizeBytes $size
#Mount/Format and Recursively Copy Items
        Mount-VHD $vhdpath -Passthru | Initialize-Disk -Passthru | New-Partition -UseMaximumSize | 
        Format-Volume -FileSystem NTFS -NewFileSystemLabel $volumename -Confirm:$false
            $drive = gwmi win32_volume -Filter "DriveLetter = null"
            $drive.DriveLetter = "B:"
            $drive.Put()
        Copy-Item -Force -Recurse -Verbose $dir -Destination "B:\" -ea SilentlyContinue
#Dismount
Dismount-VHD $vhdpath
于 2013-09-17T05:32:38.107 回答
2

有点晚了,但我只是在处理同样的问题。这是我发现的作品。

#Get the size of the folder
$FolderSize = (Get-ChildItem $ExportFolder -recurse | Measure-Object -property length -sum)
#Round it and convert it to GBs
[uint64]$Size = "{0:N0}" -f ($FolderSize.sum / 1GB)
#Add 1GB to make sure there is enough space
$Size = ($Size * 1GB) + 1GB
#Create the VHD
New-VHD -Path $VHDXFile -Dynamic -SizeBytes $Size

希望它可以帮助那里的人

于 2016-01-08T19:21:52.247 回答
2

这就是我在使用配置文件进行服务器构建时解决此问题的方法:

# Get a string of the desired size (#KB, #MB, #GB, etc...)
$size_as_string = "4GB"

# Force PowerShell to evaluate the string
$size_as_bytes = Invoke-Expression $size_as_string

Write-Host "The string '$size_as_string' converts to '$size_as_bytes' bytes"
于 2019-09-12T22:10:03.793 回答