Handling Credentials as Parameters

by Sep 20, 2018

Credentials are objects that contain a user name and an encrypted password. If your PowerShell functions should be able to accept credentials, assign the PSCredential type:

function Connect-Server
{
    param
    (
        [Parameter(Mandatory)]
        [pscredential]
        $Credential
    )
    
    "You entered a credential for {0}." -f $Credential.UserName
    # now you could do something with $Credential, i.e. submit it to
    # other cmdlets that support the -Credential parameter
    # i.e.
    # Get-WmiObject -Class Win32_BIOS -ComputerName SomeComputer -Credential $Credential    
    
}

When you run the code above, then call your function, a dialog opens and prompts for username and password. The same happens when you specify a user name: again, a dialog opens and prompts for the password, then converts your input into a proper PSCredential object:

 
PS> Connect-Server -Credential tobias  
 

This auto conversion is only available for PowerShell 5.1 and better. In previous PowerShell versions, you would have to submit a credential object in the first place. To enable the conversion in older PowerShell versions, too, you can add an additional conversion attribute:

function Connect-Server
{
    param
    (
        [Parameter(Mandatory)]
        [pscredential]
        [System.Management.Automation.Credential()]
        $Credential
    )
    
    "You entered a credential for {0}." -f $Credential.UserName
    # now you could do something with $Credential, i.e. submit it to
    # other cmdlets that support the -Credential parameter
    # i.e.
    # Get-WmiObject -Class Win32_BIOS -ComputerName SomeComputer -Credential $Credential    
    
}

Twitter This Tip! ReTweet this Tip!