Skip to content

Instantly share code, notes, and snippets.

@andyzib
Created March 21, 2017 16:32
Show Gist options
  • Save andyzib/882c99a4aa00fff8ed2a6569557e7030 to your computer and use it in GitHub Desktop.
Save andyzib/882c99a4aa00fff8ed2a6569557e7030 to your computer and use it in GitHub Desktop.
PowerShell: Credential with two username formats
# I needed two credential objects, one with username, the other DOMAIN\username.
# Same account, just different formats for username required.
# Use Get-Credential unless you have a special case like this one.
$valid_user = $false
# Infinite loop until proper username is entered.
while (-Not $valid_user) {
Write-Host "Enter username in DOMAIN\username format." -ForegroundColor DarkCyan
Write-Host "Press Ctrl+C to exit script." -ForegroundColor DarkCyan
$username = Read-Host -Prompt "Username"
$username = $username.Trim()
$valid_user = $username.Contains("\")
if (-Not $valid_user) { Write-Host "ERROR! Enter username in DOMAIN\username format." -ForegroundColor Red }
}
# Read in the password as a Secure String.
$secureString = Read-Host -AsSecureString -Prompt "Enter password for $username"
# Domain\Username Credential object.
$DomainCred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$secureString
# Trim the DOMAIN\ from username.
$username = $username.Substring($username.IndexOf("\")+1)
# Username Credential object.
$UsernameCred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$secureString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment