Created
March 21, 2017 16:32
-
-
Save andyzib/882c99a4aa00fff8ed2a6569557e7030 to your computer and use it in GitHub Desktop.
PowerShell: Credential with two username formats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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