Thursday, 10 May 2018

How to get password from user with a mask using Powershell

You can easily prompt and ask input from user by using the Read-Host cmdlet, but by default this command accepts the user input as plain text. If you get some secured data like password from user by using this command, when user type the input the password text will be clearly visible as shown in below example.
PS C:\> Read-Host "Enter password"
Enter password: myPassword
myPassword
If you want to hide or mask the password text from user, then you need to just pass the parameter –AsSecureString with Read-Host powershell command.
PS C:\> Read-Host "Enter password" -AsSecureString
Enter password: **********
System.Security.SecureString
The hard part of the above step is, it will read password as SecureString object not as clear text value. Most of the powershell commands (i.e. Set-ADAccountPassword, Set-MsolUserPassword , etc..) will accept the password input only as SecureString object, you don't need to worry if you are going to use the password with these kind of commands, but if you need that secured text for some other purpose then you should convert the secure string password to clear text password.

The following powershell code shows how to convert secure password into plain text password.

#Step 1: get secure password from user.
$securePwd = Read-Host "Enter password" -AsSecureString
#Step 2: convert secure password into normal plain text password.
$plainPwd =[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePwd))
Write-Host "You password is : $plainPwd" -ForegroundColor Yellow

Advertisements
Advertisements

No comments:

Post a Comment