Question

I created a random password generator, I need to Out-File all 10 outputs into a .txt file

But what I have now only has 1 line of the output.

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

}

When I open the .txt I just see 1 line of the output instead of 10.

Was it helpful?

Solution

By default Out-File clobbers (overwrites) at the specified path if it exists. If the file doesn't exist prior script execution, use -Append to append to the file:

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

Note that this will append to the file each time the script is run. If you want the file to be recreated each time, check existence and delete it before entering the for loop:

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

OTHER TIPS

You need to use the -Append parameter for the Out-File cmdlet, because by default it will overwrite the specified file.

Out-File .\Documents\L8_userpasswords.txt -InputObject $pwd -Append;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top