I am new to powershell. I am stuck with a problem, can you please help me out?
I have the following:
$firstname = @("Harris", "Robin", "Jack", "Ryan")
$lastname = @("Brown", "Amber", "Layton", "Hatvani")
from this 2 array I have to create a password and the criteria is take the first letter from first and lastname then 5 random numbers with them. example: hb69248 (in this case h is the first letter of Harris, b is the first letter of Brown). This has to be done for each of the names. I tried the following:
[string]$p = for ($i=0; $i -lt $firstname.count; $i++)
{ $firstname[$i].substring(0,1)}
[string]$n = for ($r=0; $r -lt 4; $r++)
{ get-random -minimum 0 -maximum 9)
$password = "$p", "$n" -join ""
The output should be like HRJR2876 (the numbers are creating randomly). But I am getting H R J R2 8 7 6. can you guys tell me why I am having the space in between them??in this case I just worked with the firstname not with the last name
When you cast an array to a string (like you do $p
and $n
), PowerShell uses the output field separator - represented by the $OFS
automatic variable - as a delimiter. $OFS
defaults to a space.
You can produce the passwords in a single loop, like this:
$passwords = for($i = 0; $i -lt $firstname.Length; $i++){
$first = $firstname[$i].Substring(0,1)
$last = $lastname[$i].Substring(0,1)
$number = Get-Random -Min 10000 -Max 100000
$first,$last,$number -join ''
}
$passwords
is now an array of all 4 new passwords