【问题标题】:I can't 'Out-File' my whole loop just one line我不能只用一行“输出文件”我的整个循环
【发布时间】:2014-03-13 15:01:09
【问题描述】:

我创建了一个随机密码生成器,我需要将所有 10 个输出输出到一个 .txt 文件中

但我现在只有 1 行输出。

for ($i=1; $i -le 10; $i++){
$caps = [char[]] "ABCDEFGHJKMNPQRSTUVWXY"
$lows = [char[]] "abcdefghjkmnpqrstuvwxy" 
$nums = [char[]] "2346789"
$spl = [char[]] "!@#$%^&*?+"

$first = $lows | Get-Random -count 1;
$second = $caps | Get-Random -count 1;
$third = $nums | Get-Random -count 1;
$forth = $lows | Get-Random -count 1;
$fifth = $spl | Get-Random -count 1;
$sixth = $caps | Get-Random -count 1;

$pwd = [string](@($first) + @($second) + @($third) + @($forth) + @($fifth) + @($sixth))
Write-Host $pwd

Out-File .\Documents\L8_userpasswords.txt -InputObject $pwd

}

当我打开 .txt 时,我只看到输出的 1 行而不是 10 行。

【问题讨论】:

    标签: powershell powershell-ise


    【解决方案1】:

    默认情况下,Out-File 会在指定路径(如果存在)处破坏(覆盖)。如果文件不存在之前的脚本执行,使用-Append 追加到文件:

    Out-File .\Documents\L8_userpasswords.txt -InputObject $pwd -Append
    

    请注意,每次运行脚本时,这都会附加到文件中。如果您希望每次都重新创建文件,请在进入for 循环之前检查是否存在并删除它:

    $file = ".\L8_userpasswords.txt"
    if (Test-Path -Path $file -PathType Leaf) {
        Remove-Item $file
    }
    for ($i=1; $i -le 10; $i++){
    ...
    

    【讨论】:

      【解决方案2】:

      Out-File cmdlet 需要使用-Append 参数,因为默认情况下它将覆盖指定的文件。

      Out-File .\Documents\L8_userpasswords.txt -InputObject $pwd -Append;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-09
        • 1970-01-01
        • 2021-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多