0
votes

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!

1
Thanks, i have the mapping working ok, I just want to have a loop... I was trying a try{} catch{} finally{} for the loop but this kept popping up the credential box even if they had been entered correctlyuser1130264

1 Answers

1
votes

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"