Skip to main content

PowerShell helper function to convert a plain-text username and password to a PSCredential object.

function ConvertTo-PSCredential
{
    <#
    .SYNOPSIS
        Converts an user and password to PSCredential object.

    .PARAMETER User
        User.

    .PARAMETER Password
        Password.

    .EXAMPLE
        $psCredential = ConvertTo-PSCredential -User "User" -Password "pass"
    #>

    [CmdletBinding()]
    [OutputType([System.Management.Automation.PSCredential])]
    param(
        [Parameter(Mandatory = $false)]
        [string]
        $User,

        [Parameter(Mandatory = $true)]
        [string]
        $Password
    )

    $pass = ConvertTo-SecureString -String $Password -AsPlainText -Force

    if (!$User)
    {
        $User = "<none>"
    }

    return (New-Object System.Management.Automation.PsCredential $User, $pass)

}