Powershell TextBox SecureString

23,209

Solution 1

Use a MaskedTextBox instead of a regular TextBox if you want to embed this in a custom GUI:

Add-Type -Assembly 'System.Windows.Forms'

$form = New-Object Windows.Forms.Form

$password = New-Object Windows.Forms.MaskedTextBox
$password.PasswordChar = '*'
$password.Top  = 100
$password.Left = 80

$form.Controls.Add($password)

$form.ShowDialog()

[source]

and then convert the text to a secure string:

$secstr = $password.Text | ConvertTo-SecureString -AsPlaintText -Force

If you just want to prompt for credentials you could use Get-Credential, which already stores the entered password as a secure string:

PS C:\> $cred = Get-Credential

Cmdlet Get-Credential an der Befehlspipelineposition 1
Geben Sie Werte für die folgenden Parameter an:
Credential
PS C:\> $cred.Password
System.Security.SecureString

Solution 2

An additional way is to use a plain TextBox and as Ansgar mentioned use the PasswordChar attribute:

$textbox = New-Object System.Windows.Forms.Textbox
$textbox.Size = '75,23'
$textbox.PasswordChar = '*'
$form.Controls.Add($textbox)
Share:
23,209

Related videos on Youtube

LTrig
Author by

LTrig

PowerShell novice but eager to expand my knowledge.

Updated on May 21, 2020

Comments

  • LTrig
    LTrig about 4 years

    Is it possible using the System.Windows.Forms.TextBox (or any other method) to enter in text that can then be converted to securestring? I would like to be able to take a value entered, convert it to securestring and write that to a file which could then be called on if needed and the securestring converted back should we need to identify the value.

    I've looked into something similar to this, but since I am using the TextBox forms, I don't want to rely on Read-Host

    $secstr = Read-Host -AsSecureString "Enter your text"
    
    $secstr | ConvertFrom-SecureString | out-file C:\temp\test.txt
    
    $secstr = get-content c:\temp\test.txt | ConvertTo-SecureString -AsPlaintText -Force
    

    Essentially, I want to have a text box use masked/password characters (which I can do with $TextBox.PasswordChar = "*" and then take that input and dump it into a securestring text file. Then, I could use another script to call on that file and display the text in plain text for the end user should they need to know that current value.