powershell - 使用随机数据创建文件的最快方法

标签 powershell

我需要创建填充随机数据的指定大小的文件。
我不能使用任何第三方工具来实现这一点,所以我可以使用的只是 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/

相关文章:

使用 Get-ChildItem 存储到数组时,Powershell Item-Property 未展开

PowerShell:打开和关闭 "Num Lock"。

PowerShell:如何从源目录中仅复制选定的文件?

python - 作为 .py 运行时出现随机模块错误

powershell - 导入 CSV 并搜索结果

api - Azure Advisor API 可能的限制和筛选问题

c# - 使用 C# 从 Powershell 中解密 SecureString

powershell - 如何避免 PowerShell 内联文档中的换行符

python - 通过 Powershell Invoke-RestMethod 上传分段文件

powershell - 远程机器上的调用命令无法使用 powershell