powershell - 通过powershell创建2个带有随机内容的文本文件
问题描述
我想通过 powershell 创建 2 个带有随机内容的文本文件。但是,我得到了非常奇怪的字符。我们如何创建带有字母数字字符的随机内容?
for ($i=1; $i -le 2; $i++)
{
$out = new-object byte[] 1073741824; (new-object Random).NextBytes($out); [IO.File]::WriteAllBytes("c:\temp\file$i.txt", $out)
}
输出 :
Àº"”x¯'p¦²5ÐÃ?•š‚«ÉPj×æȵ¼ÛZxD¶GH 6¤rå›èKˆÍÖŒwûó>X±) È_UðõYv¡°ûÖ»LyàÞ8ä´‚‹^úD(Dàf:ë§X×O‚ïBrª×ÒÿÑ*‚`Õsý¦jdÈ°yf«Ò
96: ¤! Ž¶õrá†(DW^TÙ.ww’ír>¹>ÈbC,Â-4…` Ñ~Š–4ä<Ìq–»|—Ê&4—Pý·ª®Ze"”ýJù}á^ 6qH§¬§¶¯+bs,r€!Çàè–‰ÖµNp„lžM
解决方案
我想我会创建一个快速可重用的函数,它将获取您想要的字符串的长度并输出如下:
$filepath = "C:\file1.txt"
$filepath2 = "C:\file2.txt"
#-lines is the number of lines you want. -length is the length of each line.
$file1 = Get-RandomAlphaNum -lines 2 -length 250
$file2 = Get-RandomAlphaNum -lines 4 -length 250
$file1 | Out-File -FilePath $filepath
$file2 | Out-File -FilePath $filepath2
Function Get-RandomAlphaNum {
[CmdletBinding()]
Param (
[int] $length = 0,
[int] $lines = 1
)
$output = "";
# Create specified $number of -lines
for ($num = 1 ; $number -le $lines; $number++) {
# create an alphanum line of specified -length
$output += -join ((0x30..0x39) + ( 0x41..0x5A) + ( 0x61..0x7A) | Get-Random -Count $length | ForEach-Object {[char]$_;});
# This adds you newline/carriage return at the end of each line
$output += "`r`n"
}
return $output
}
您可以添加一个乘数,插入一些换行符,或者满足您正在寻找的任何最终输出的任何内容。例如,您可以添加一个循环,为每个长度计数生成 8 个字符,并在其间插入一个空格。
推荐阅读
- c++ - QtCreator 上对 opencv dnn 的未定义引用
- python - 每 5 分钟轮换一次日志文件
- swift - 实例化效果时 AudioKit 内存泄漏
- node.js - Electron Node fs.writefile 承诺中间失败
- python - 无法跳出我想要的循环
- django - (Wagtail)字段定义与模型“wagtailimages.Images”的关系,该模型要么未安装,要么是抽象的
- c++ - 在 *nuspec 文件中指定体系结构和调试/发布模式以发布 DLL C++ 项目
- apache-fop - 在 eXist-db 中处理带有 FOP 的 XSL-FO 文件以“权限被拒绝”退出(仅在 Linux 上)
- sql - 从 SQL 代理运行时 PowerShell 脚本失败
- .net - 当有大量可用内存时,跨不同应用程序池的多个 OutOfMemoryException