Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

script to map drives in powershell

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 \servernameshare -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 \servernameshare -Persist -Credential $Credential -ErrorAction Stop
New-PSDrive -Name "T" -PSProvider  FileSystem -Root \servernameshare -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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 \servershare -Persist -Credential $Credential -ErrorAction Stop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...