繁体   English   中英

powershell 中 map 驱动器的脚本

[英]script to map drive in powershell

我正在尝试创建一个 ps1 脚本,它将用户 AD 密码作为变量,然后将其传递给 New-Psdrive 命令行开关。 他们映射的驱动器是共享的,因此如果他们输入正确的凭据,它将 map,无需检查 AD 以获取正确的用户名/密码。

我希望能够在脚本退出之前给他们 3 次输入正确凭据的机会。

到目前为止我有

$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

当被调用时,我得到一个用户名/密码框,如果凭据正确,则驱动器被映射,但如果凭据不正确,我希望该框弹出,如果再次输入错误的,可能会再次发生

我做到了

尝试 {$Credential = $host.ui.PromptForCredential("需要凭据", "请输入您的用户名和密码。", "", "NetBiosUserName") New-PSDrive -Name "T" -PSProvider FileSystem -Root \servername -Persist -Credential $Credential -ErrorAction Ignore} catch {write-host "incorrect, try again"}

然后重复这个,但是当凭证正确时,仍然会弹出凭证window

谢谢你的帮助!

试试这个,我添加了一个测试,因为如果用户取消凭据对话框,将创建 PSDrive:

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM