I am building a program for our maintenance guys at work to give them controlled access to some files we do not want our operators to have access to. The function down below is to capture credentials and I have it set up so if the "X" in the corner is hit or "CANCEL" is they will be re-prompted to enter their credentials. However if they hit "ok" while a username is entered but not a password they don't get re-prompted. How can I make that happen?
function Get-Creds {
Add-Type -AssemblyName System.Windows.Forms
do{
$cred = $host.ui.PromptForCredential("Authenticate to OSD:", "Please enter your Operator Credentials", "", "")
if(-not $cred){
[System.Windows.Forms.MessageBox]::Show("Credentials cannot be empty!")
Get-Creds
continue
}
# ...
$done = $true
} until ($done)
}
CodePudding user response:
You can add a check if the input password was blank, for this you can use String.IsNullOrWhiteSpace(String)
Method to test if the password is null and to decrypt the password of the PSCredential
Object, you can construct a new instance of NetWorkCredential
targeting the NetworkCredential(String, SecureString)
overload then call the .Password
of the instance which returns a string (decrypted password).
if([string]::IsNullOrWhiteSpace([Net.NetworkCredential]::new('', $cred.Password).Password)) {
[System.Windows.Forms.MessageBox]::Show("Password cannot be empty!")
Get-Creds
continue
}