Jump to content

[PowerShell] - Why does this script generate spaces between every character of a password?


0phoi5

Recommended Posts

Hi all,

I am using the following;
 

Quote

 

Do {

$password = $null

$characters = ‘abcdefghkmnprstuvwxyzABCDEFGHKLMNPRSTUVWXYZ12346789!£$%^&*()?’

$random = 1..10 | ForEach-Object { Get-Random -Maximum $characters.length }

$password = [String]$characters[$random]

} Until ($password -match "[0-9]")

 

 

This outputs passwords with spaces in-between every character, for example "P ! A r g k X 7 n g".

I want the password to have no spaces, for example "P!ArgkX7ng".

I can achieve this by using the following;

Quote

$password_nospace = ($password -replace "\s","")

However I'm pretty sure I'm doing something wrong in the above to make the password produce with spaces in it?

Thanks.

Link to comment
Share on other sites

You took an array and casted it to a string.  Expect spaces whenever you do that.  Correct way to handle this is to use "join".

$password = -join ($characters[$random])

if you are looking for a random password generator, here is a oneliner.

$password = -join (33..126 | ForEach-Object {[char]$_} | Get-Random -Count 20)

The count is your total number of characters in password you want.  The 33..126 is the int values for all printable ascii values..well the ones that are in series.  You can of course extend this in a loop and then test to see if it meets your complexity after each run until it matches.

  • Like 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...