2014-03-13 23 views
3

我創建了一個隨機密碼生成器,我要出文件中的所有10個輸出到一個txt文件我不能「出文件」我的整個循環只有一行

但是我現在只有1行輸出。

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

$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

回答

5

默認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++){ 
... 
1

您需要使用-Append參數爲Out-File cmdlet的,因爲默認情況下它會覆蓋指定的文件。

Out-File .\Documents\L8_userpasswords.txt -InputObject $pwd -Append; 
相關問題