If you ever write PowerShell functions that need to accept sensitive input such as passwords, make sure you allow users to submit SecureString input. If you accept passwords via clear text, there is a substantial risk that others may see the password while being entered, or (even worse) that the password is logged and later can be found in dump files.

Here is a simple framework that illustrates how you can achieve safe input:

function Enter-Secret
{
    param
    (
        [Parameter(Mandatory)]
        [SecureString]
        $SafeInput
    )

    $PlainText = [Management.Automation.PSCredential]::
    new('x',$SafeInput).GetNetworkCredential().Password

    "User entered $PlainText"

}

When the user runs Enter-Secret, the password can be entered in a masked way. Internally, the function converts the secure string into plain text. This way, the secret password is never visible and will never be logged.

The conversion from SecureString to String is performed by creating a temporary credential object. Credential objects have a built-in method (GetNetworkCredential()) to convert a SecureString to a String.


Twitter This Tip! ReTweet this Tip!

Anonymous