我需要创建一个填充了随机数据的指定大小的文件.我不能使用任何第三方工具来实现这一点,所以我所拥有的只是所有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
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来创建随机数据的文件?我正在生成GUID,然后将它们写入文件.
Lie*_*ers 10
下面将一组随机字节写入文件,但速度仍然很快
编辑
Kudos到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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2275 次 |
最近记录: |