Home > Net >  create user with respone if success and two inputs of the password
create user with respone if success and two inputs of the password

Time:10-02

i want to create a local admin account. how can i realize a output if the operation was successfull or not? and how can i realize that i need to input the same password twice for safety reasons for example i made a mistake? if the passwords are incorrect i need to type them again

$admin = read-host "Name"
$Password = Read-Host "Passwort" -AsSecureString
        New-LocalUser -Name "$admin" -password $password -Description "$admin" -FullName      "$admin" 
        Add-LocalGroupMember -Name "administrators" -Member "$admin"
        Set-LocalUser -Name "$admin" -PasswordNeverExpires 1 -AccountNeverExpires -UserMayChangePassword 0

CodePudding user response:

You can do that in a endless loop.

Something like below:

$userName          = Read-Host "Name"
$securePassword    = Read-Host "Password" -AsSecureString
$plainTextPassword = [System.Net.NetworkCredential]::new("someone", $securePassword).Password
while ($true) {
    $securePassword2 = Read-Host "Retype the password. Leave empty to cancel." -AsSecureString
    # convert the SecureString to plain text
    $plainTextPassword2 = [System.Net.NetworkCredential]::new("someone", $securePassword2).Password
    if ([string]::IsNullOrWhiteSpace($plainTextPassword2)) { return }  # cancel: exit the script
    if ($plainTextPassword -ceq $plainTextPassword2) { break }         # both passwords are equal, break the loop
}

try {
    $newUser = New-LocalUser -Name $userName -Password $securePassword -Description $userName -FullName $userName -ErrorAction Stop
    $newUser | Set-LocalUser -PasswordNeverExpires $true -UserMayChangePassword $false -AccountNeverExpires -ErrorAction Stop
    Add-LocalGroupMember -Group "Administrators" -Member $userName -ErrorAction Stop
}
catch {
    throw $_.Exception.Message
}
  • Related