VMware Cloud Community
DCasota
Expert
Expert

Optimized code snippet <li-code lang="powershell"> for random root password for vmhost

Hi, I want an optimized code snippet <li-code lang="powershell"> for random root password for vmhost. Any suggestions are welcome.

 

# count 12, at least 1 upper case letter, at least 1 lower case letter, at least one digit
$newpassword=""

$Length=12
$MinUpperCaseCount=1
$MinLowerCaseCount=1
$MinChiffresCount=1
$LengthPart=$Length-$MinUpperCaseCount-$MinLowerCaseCount-$MinChiffresCount
$regex=[regex]"(?=.{$MinChiffresCount,$LengthPart}\d)(?=.{$MinLowerCaseCount,$LengthPart}[a-z])(?=.{$MinUpperCaseCount,$LengthPart}[A-Z])[a-zA-Z\d]{$Length,$Length}"

while ($newpassword -eq "")
{
    try{
        $newpasswordraw= [GUID]::NewGuid().ToString('N') + [GUID]::NewGuid().ToString('N').ToUpper()
        $newpassword=-join ((($regex.matches($newpasswordraw)).value).ToCharArray() | sort-object {get-random})
    }
    catch{}
}
if ($newpassword -ne "")
{
    Set-VMHostaccount -Useraccount root -Password $newpassword
    write-host "Set new password $newpassword done."
}

 

 

Tags (2)
0 Kudos
2 Replies
LucD
Leadership
Leadership

Is there a question in here?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
DCasota
Expert
Expert

Spoiler
The sequence while-try-if bothered me.
0 Kudos