What's the most secure way to ask for / pass in credentials?

I have a script that I want to ask the user who runs it to type in credentials - I don’t want to use pscredential - because it prompts for a username - which I DON’T need:

[CmdletBinding()]
Param (   
    [Parameter(ValueFromPipeline = $True, Mandatory = $False)]
    [ValidateNotNull()]
    [SecureString]$Credential,

)

if (-not $Credential) {
    Write-Host "Please enter a password for the new user:"
    $Credential = Read-Host -AsSecureString
}

Is this bad practice? Is there a better way to ask for credentials - the only ways I know are with pscredential which relies on Get-Credential. Is this not secure?

This is incorrect. You can specify the username

Get-Credential username

Get-Credential username@domain.com

Get-Credential domain\username

Now if you don’t want the user to see and/or be able to change the username, then Read-Host -AsSecureString would be the way to go. However, I’d still use a pscredential

$securepassword = Read-Host "Please enter a password for the new user" -AsSecureString
$credential = New-Object PSCredential $username, $securepassword
2 Likes

Perfect thank youuuuu