首页 > 解决方案 > 通过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–»|—Ê&amp;4—Pý·ª®Ze"”ýJù}á^        6qH§¬§¶¯+bs,r€!Çàè–‰ÖµNp„lžM

标签: powershell

解决方案


我想我会创建一个快速可重用的函数,它将获取您想要的字符串的长度并输出如下:

$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 个字符,并在其间插入一个空格。


推荐阅读