Reputation: 23
Complete Powershell Noobie here.
I have a .bat
file that I would like to convert to Powershell.
Basically when run; it asks the user to enter their Active Directory credentials. Once validated; it starts a RSAT tool (example: dhcpmgmt.msc
) as the elevated domain user.
However, if credentials are incorrect (if %ERRORLEVEL% EQU 5
); it does a GOTO an echo "Incorrect username and password"
and then loops back requesting the user to enter their credentials again.
When I use:
do
{
Start-Process -FilePath C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Credential (Get-Credential "$env:USERDNSDOMAIN\") -ArgumentList "C:\Windows\System32\dhcpmgmt.msc"
} until ($response -eq $null)
It works. But if I enter an incorrect password; the window closes.
I would like a notification information the user that the Username/Password is incorrect and then re-direct them to enter their credentials again. This would loop until either the user enters the correct credentials or simple clicks the cancel button.
Any help/guidance is highly appreciated. Thanks a bunch in advance!
Upvotes: 2
Views: 306
Reputation: 11364
You can run this in the while loop to keep asking for credentials until they are valid.
while ($true)
{
$userCreds = Get-Credential "$env:USERDNSDOMAIN\"
try {
Start-Process powershell -Credential $userCreds -ArgumentList "C:\Windows\System32\dhcpmgmt.msc" -ErrorAction Stop
break
}
catch {
Write-Output "Invalid Credentials"
Write-Output "Enter new credentials?"
if ((Read-Host) -ne "Yes") { break }
}
}
Upvotes: 1
Reputation: 3264
This should do the needful.
Loop
to Get and Check Credential
Try
-Catch
Credential CheckMessagebox
on Failed CredentialExit
script on Cancel
.$Credential=$null
while ($Credential -eq $null) {
$Credential = Get-Credential -Username "$env:USERDNSDOMAIN\" -message "Enter Admin Password"
try {
Start-Process -FilePath cmd.exe /c -Credential $Credential
}
catch {
$Credential=$null
IF (
$([System.Windows.MessageBox]::Show('Invalid UN/PW! ?','Credential Error','OKCancel','Error')
) -eq "Cancel") { EXIT}
}
}
### Your code to launch RSAT tools here:
We use a while
loop.
While the credentials are NULL we p, getting the credentials, storing it as a secure string in a variable, then do a try-catch on the test of running a process, if that will try to get the credentials again, and we store the credentials in a variable as a secure string.
Initially, credentials are NULL
so we ask for them.
Then we use Try
to test the credentials by initiating a process as them.
If that fails we Catch
it and 1st set credentials to NULL
again, then we Raise a Windows Message Box
to the user letting them know the credentials failed and checking if they would like to try again (OK
) or Cancel
.
If they respond with Cancel, there is no point in continuing the script so we just exit
.
Otherwise, we just go ahead with our loop as planned
Upvotes: 0