How to Securely Handle Passwords with PowerShell Read-Host?

In this tutorial, I will explain how to use PowerShell’s Read-Host cmdlet to securely handle passwords in your scripts. It is crucial to ensure that the input is secure and not displayed in plain text when handling passwords. Read-Host PowerShell cmdlet provides an option to handle passwords securely.

Read-Host with -AsSecureString for Password Input

To prompt for a password and mask the input, you can use the -AsSecureString parameter of the PowerShell Read-Host cmdlet. Here’s a basic example:

$password = Read-Host "Enter your password" -AsSecureString

This command will display “Enter your password:” as a prompt, and as the user types, asterisks (*) will appear on the console instead of the actual characters, providing a secure way to input sensitive information.

Convert SecureString to Plain Text

While it is generally not recommended to convert secure strings to plain text due to security risks, there are scenarios where you might need to use the password in plain text. Here’s how you can convert a secure string to plain text using the below PowerShell script:

$password = Read-Host -Prompt "Enter your password" -AsSecureString
$plainTextPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

This script captures the password as a secure string and then converts it to plain text using .NET methods. Use this approach cautiously and ensure that plain text passwords are handled securely.

Now, let me show you a few real examples of using the Read-Host for password input.

Example 1: Authenticate a User

Suppose you’re creating a script to authenticate a user for accessing a secure database in a New York-based financial firm:

$username = Read-Host "Enter your NYFIN username"
$password = Read-Host "Enter your NYFIN password" -AsSecureString

# Here you would typically use these credentials for authentication
# For demonstration purposes, we'll just print a success message
Write-Host "Authentication successful for user: $username"

Here is the exact output you can see in the screenshot below:

powershell read-host password

Check out How to Use PowerShell Read-Host with Default Values?

Example 2: Change a Password

Here’s an example of how you might use Read-Host to change a user’s password:

$currentPassword = Read-Host "Enter your current password" -AsSecureString
$newPassword = Read-Host "Enter your new password" -AsSecureString
$confirmPassword = Read-Host "Confirm your new password" -AsSecureString

# Here you would typically implement password change logic
# For demonstration, we'll just print a success message
Write-Host "Password changed successfully for user: $env:USERNAME"

Using Get-Credential for Secure Input

Another method to handle passwords securely is to use the Get-Credential cmdlet, which prompts the user for a username and password and returns a credential object.

$credential = Get-Credential

This command opens a dialog box where the user can enter their username and password securely. The resulting credential object can be used in various security contexts within your script.

Check out How to Use PowerShell Read-Host to Enter Multiple Lines?

Using .NET Classes for Masked Input

For a more user-friendly approach that masks input with asterisks, you can use .NET classes. This method involves creating a custom function that captures input while displaying asterisks.

Example

Here is an example and the complete PowerShell script.

function Read-Host-Masked ($prompt) {
    $password = ""
    $secstr = [System.Security.SecureString]::new()
    Write-Host $prompt
    while ($true) {
        $key = [System.Console]::ReadKey($true)
        if ($key.Key -eq 'Enter') { break }
        if ($key.Key -eq 'Backspace') {
            if ($password.Length -gt 0) {
                $password = $password.Substring(0, $password.Length - 1)
                $secstr.RemoveAt($secstr.Length - 1)
                Write-Host "`b `b" -NoNewline
            }
        } else {
            $password += $key.KeyChar
            $secstr.AppendChar($key.KeyChar)
            Write-Host "*" -NoNewline
        }
    }
    Write-Host
    return $secstr
}

$password = Read-Host-Masked "Enter your password: "

This function captures each keystroke, appends it to a secure string, and displays an asterisk. It handles backspaces and stops capturing input when the Enter key is pressed.

Check out How to Use PowerShell Get-Process?

Using GUI for Masked Input in PowerShell

Another approach is to use a graphical user interface (GUI) to prompt for masked input. This method provides a more polished user experience.

Example

Here is an example and the complete PowerShell script.

Add-Type -AssemblyName System.Windows.Forms

function Get-MaskedInput {
    $form = New-Object System.Windows.Forms.Form
    $form.Text = "Enter Password"
    $form.Width = 300
    $form.Height = 150

    $label = New-Object System.Windows.Forms.Label
    $label.Text = "Password:"
    $label.Left = 10
    $label.Top = 20
    $form.Controls.Add($label)

    $textbox = New-Object System.Windows.Forms.TextBox
    $textbox.Left = 100
    $textbox.Top = 20
    $textbox.Width = 150
    $textbox.UseSystemPasswordChar = $true
    $form.Controls.Add($textbox)

    $buttonOK = New-Object System.Windows.Forms.Button
    $buttonOK.Text = "OK"
    $buttonOK.Left = 100
    $buttonOK.Top = 60
    $buttonOK.DialogResult = [System.Windows.Forms.DialogResult]::OK
    $form.Controls.Add($buttonOK)

    $form.AcceptButton = $buttonOK

    if ($form.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
        return $textbox.Text
    }
}

$password = Get-MaskedInput

This script creates a simple form with a masked text box for password input. The password is returned as plain text, so handle it securely.

Using Read-Host with the -AsSecureString parameter is an effective way to securely prompt for passwords in PowerShell. For enhanced security and convenience, consider using the Get-Credential cmdlet, which encapsulates both username and password securely. I hope you now have an idea of how to handle passwords using the Read-Host cmdlet and the -AsSecureString parameter.

You may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.