PowerTip: Convert Plain Text to Secure String


Summary: Learn to convert a plain text password to a secure string for cmdlet parameters.

 Hey, Scripting Guy! Question I'm trying to convert some scripts to work with the Active Directory modules, 
           but they need a secure string for the password. How do I create one of these?

Hey, Scripting Guy! Answer Use the ConvertTo-SecureString cmdlet, capture the output, then
           supply the new variable as SecureString for the password:

$SecurePassword=ConvertTo-SecureString 'MySuperSecretP@ssw0rd!' –asplaintext –force 

Comments (5)

  1. Graeme Bray says:

    Sure would be nice to have this implemented so we can truly do some secure credential storage…
    https://connect.microsoft.com/PowerShell/feedback/details/907144/cmdlets-to-support-credentials-management-with-credential-manager

    Please upvote.

  2. James Brown says:

    $pw = Read-host -AsSecureString "Enter password…"

    $pw = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))

    This will obtain a password securely using asterisks and won’t be visible in the command history.

  3. James Brown says:

    Re-submitted for formatting clarity:

    $pw = Read-host -AsSecureString "`nEnter password…"
    $pw = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto`
    ([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))

  4. ed wilson says:

    @James Brown you are right, using Read-Host is a good way to get a secure string and to mask the input. But the scenario above was to do it in a script, and therefore the need to not be interactive.

Skip to main content