script to map drives in powershell

0

I need to be able to map a couple of drives via a Powershell script during computer logon. The script I have so far (thanks to help on this forum) is below

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"

The problem is, when I add another drive to be mapped under the one above, like this

New-PSDrive -Name "P" -PSProvider  FileSystem -Root \\servername\share -Persist -Credential $Credential -ErrorAction Stop
New-PSDrive -Name "T" -PSProvider  FileSystem -Root \\servername\share -Persist -Credential $Credential -ErrorAction Stop

the script just loops with "wrong username/password....." message

If I comment out either drive mapping line it works fine

any help would be appreciated Thanks

powershell
asked on Stack Overflow Jan 8, 2021 by user1130264 • edited Jan 8, 2021 by Olaf

1 Answer

0

try only this to see the error

    Remove-PSDrive -Name T
    $Credential=$null
    $Credential = $host.ui.PromptForCredential("Need credentials", "Please enter your user name and password.", "", "NetBiosUserName")
    New-PSDrive -Name "T" -PSProvider  FileSystem -Root \\server\share -Persist -Credential $Credential -ErrorAction Stop
answered on Stack Overflow Jan 8, 2021 by Kemal K.

User contributions licensed under CC BY-SA 3.0