Unexpected output from function when used in a Foreach construct

by Aug 1, 2014

Hello Mods, and Members,

I'm new to PS scripting (not to programming or CS) and could use some assistance in debugging a simple function and use of that function. I've been through the powershell 3.0 step-by-step book twice, and amongst my other Google searches, I just can't seem pin-point my error.


1.Write a function that generates a random password, the password cannot contain specific special characters, but all others in the range are allowed.

2. Use the function to produce a .csv file containing 50 generated passwords.

Here's the code for the function:

function Get-RandomPassword([int]$maxChars = 8) {
    $NewPassword=""    # Null out previous password (if any)
    $rand = New-Object System.Random      # Create random object
    $badCharAry = 34,39,40,41,44,47,58,59,63,96,123,124,125
    $i = 0
    $isBadChar = $FALSE
    # For each iteration up to maxChars, get a rondom character, check character is valid
    while ($i -lt $maxChars) {
        do {
            $num = $rand.Next(33,127)
            switch ($num) {
                {$_ -in $badCharAry} {$isBadChar = $TRUE}
                Default {$isBadChar = $FALSE}
        } while ($isBadChar)
        $NewPassword += [char]$num

    return $NewPassword   #Return the new password
}# End function Get-RandomPassword

When I execute this function it returns a random password every time.

For the Second part, I believe all I need is a valid object to export to .csv, so I attempted to enumerate 50 passwords into an array and blam, export, done!

like so: $passAry = @(); 0..50 | foreach { $passAry += Get-RandomPassword }

This is the truncated output, basically it gives me 50 passwords, but only 5-7 unique ones. Strangely the number of repetitions or number of unique passwords is different each time.


Any advice or a point in the right direction would be very appreciated.