Reputation: 25
I am trying to create a ps1 script that will take a users AD password as a variable then pass that to the New-Psdrive commandlet. The drive they are mapping is shared so that if they enter the correct credentials it will map, with no need to check AD for the correct username/password.
I want to be able to give them 3 chances of entering the correct credentials before the script will exit.
So far I have
$Credential = $host.ui.PromptForCredential("Need credentials", "Please enter your user name and password.", "", "NetBiosUserName")
New-PSDrive -Name "T" -PSProvider FileSystem -Root \\servername -Persist -Credential $Credential -ErrorAction Ignore
When called i get a username/password box and if credentials are correct the drive is mapped, but I want the box to pop back up if the credentials are incorrect, and potentially happen again if the wrong ones are entered again
I got as far as
try {$Credential = $host.ui.PromptForCredential("Need credentials", "Please enter your user name and password.", "", "NetBiosUserName") New-PSDrive -Name "T" -PSProvider FileSystem -Root \servername -Persist -Credential $Credential -ErrorAction Ignore} catch {write-host "incorrect, try again"}
Then repeating this, but when the credentials are correct, it still pops up the credential window
thanks for any help!
Upvotes: 0
Views: 1632
Reputation: 1190
Try this, I added a test because PSDrive will be created if the user cancel the credential dialog :
while ($true)
{
try
{
$Credential = $host.ui.PromptForCredential("Need credentials", "Please enter your user name and password.", "", "NetBiosUserName")
# Prevent cancel that maps PSDrive anyway
if ($Credential)
{
New-PSDrive -Name "T" -PSProvider FileSystem -Root \\servername\share -Persist -Credential $Credential -ErrorAction Stop
}
else
{
throw [System.ComponentModel.Win32Exception]::new(0x80004005) # Invalid login and/or password
}
"OK"
# PSSDrive created, exiting the infinite loop
break
}
catch
{
Write-Warning "Wrong Username and/or password, please retry..."
}
}
"Continue"
Upvotes: 1