powershellexport-csv

Export-CSV exports blank file, also trying to figure out how to create a loop function


Function Get-RandoPass{

    $csv = "C:\Users\Administrator\Desktop\words.csv"
    $WordList = Import-Csv $csv

    $list1 = $WordList.List1
    $list2 = $WordList.List2
    $list3 = $Wordlist.List3
    
    $word1 = Get-Random -InputObject $list1 -Count 1
    $word2 = Get-Random -InputObject $list1 -Count 1
    $word3 = Get-Random -InputObject $list1 -Count 1
    $num1 = Get-Random -Maximum 10 -Minimum 0
    Write-Host "Random Password:" $word1$num1-$word2-$word3
}
Get-RandoPass| Export-Csv -Notypeinformation -Path C:\Users\Administrator\Desktop\test2.csv

So I'm trying to modify this script so it exports the password generated to a csv but it only exports a blank file. Not sure what I'm doing wrong on that one. The other thing I'm trying to figure out how to do is set it up so I can generate [x] number of passwords which I think I'd just have to add a switch parameter on a loop to rerun the password generation but I could be wrong. I'm pretty new to powershell.

Any ideas would be appreciated!

EDIT: Here's an example from the csv, it does generate the passwords as expected but it just doesn't export them to a csv file.

Dictionary csv


Solution

  • Your function Get-RandomPassword does not output anything..
    It just writes randomized passwords to the console window.
    That is why you pipe nothing to the Export-Csv cmdlet. What the function should do is to emit the passwords as objects

    Replace the line Write-Host "Random Password:" $word1$num1-$word2$num2-$word3$num3 with:

    [PsCustomObject]@{Password = "$word1$num1-$word2$num2-$word3$num3"}
    

    That way the function outputs an array of random password objects you can pipe through to the Export-Csv cmdlet