我需要创建填充随机数据的指定大小的文件。
我不能使用任何第三方工具来实现这一点,所以我可以使用的只是 Powershell 命令。
我这里的东西适用于大小从 1 KB 到 30 KB 的小文件。
当文件变大时,它不能很好地扩展。
function makeFile([String]$filename, [int]$SizeInKb) {
$str = ""
$size = 29 * $SizeInKb
if (-not (Test-Path $filename)) {
New-Item $filename -ItemType File | Out-Null
for ($i=1; $i -le $size; $i++) {
# A GUID is 36 characters long
# We will create a string 29*36 (1044) characters in length and
# multiply it with $SizeInKb
$str += [guid]::NewGuid()
}
write $str to a file barring the last ($SizeInKb * 20) + 2 characters.
$strip_length = ($SizeInKb * 20) + 2
("$str").Remove(0, $strip_length) | Out-File "$filename" -Encoding ascii
}
}
有没有更好的方法来创建带有随机数据的文件?
我目前正在生成 GUID,然后将它们写入文件。
最佳答案
以下将一组随机字节写入文件并且仍然非常快
编辑
感谢 Tom Blodget 指出解码/编码中的问题
$bytes = 10MB
[System.Security.Cryptography.RNGCryptoServiceProvider] $rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$rndbytes = New-Object byte[] $bytes
$rng.GetBytes($rndbytes)
[System.IO.File]::WriteAllBytes("$($env:TEMP)\test.txt", $rndbytes)
关于powershell - 使用随机数据创建文件的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49835860/