从网络驱动器复制文件时如何处理错误的登录

时间:2013-08-13 17:03:38

标签: batch-file

我有一个批处理脚本,可以将文件从网络驱动器复制到桌面。

如果我手动执行此操作,当我尝试访问网络驱动器时,偶尔会出现提示输入凭据。

当批处理脚本遇到这种情况时,它会给我一个“错误的用户名/密码”错误。我想抓住错误(有点像其他语言中的try-catch,在批处理脚本中是否有等价?)并登录到域。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

以下是我正在使用的脚本的一些摘录。这些摘录解决了与您的问题几乎完全相同的一些问题。

del dela delb /f /q 2>nul 1>nul
echo |net use %letter%: "\\%servername%\%sharename%" /persistent:YES 2>delb 1>dela
    REM this part is the cool part: the "echo |" passes "" to the net use in case it prompts for username/password.
    REM When the net use gets that input on the username prompt, it returns "user canceled the action" and we
    REM capture that later on.
findstr /r /i /c:"successfully" dela 1>nul 2>nul
if [%errorlevel%]==[0] (
    echo Success: %letter%: as \\%servername%\%sharename%
) else (
    echo Failed: %letter%: as \\%servername%\%sharename%.

    REM possible errors:
    REM 1. syserr 55: "no longer available" = folder doesn't exist.     ACTIONS: inform user, continue
    REM 2.      1223: "canceled" = wrong password/username.             ACTIONS: ask for creds, ask to re-run script.
    REM 3. syserr  3: "cannot find the path specified" = bad sharename. ACTIONS: inform user, continue
    REM 4. syserr 85: "already in use" = didn't remove old drive maps.  ACTIONS: warn user, continue
    ::type delb
    ::echo above is delb.
    set thisErr=
    findstr /r /i /c:"cannot find the path specified" delb 1>nul 2>nul
    if [%errorlevel%]==[0] set thisErr=notexists
    findstr /r /i /c:"longer" delb 1>nul 2>nul
    if [%errorlevel%]==[0] set thisErr=nolongeravailable
    findstr /r /i /c:"canceled" delb 1>nul 2>nul
    if [%errorlevel%]==[0] set thisErr=wrongcreds
    findstr /r /i /c:"already in use" delb 1>nul 2>nul
    if [%errorlevel%]==[0] set thisErr=alreadyused
    if [%thisErr%]==[wrongcreds] (
        echo Cannot connect to the server due to incorrect credentials...
        if defined TRUE (
            set /p uname=Enter the username to connect to '%servername%': 
            REM echo !uname!
            cmdkey /add:%servername% /u:!uname! /p
            REM cmdkey /add:%servername% /user:%username% /pass:%password%
        ) else (
            cmdkey /add:%servername% /u:%username% /p:%password%
        )
        ::echo Break the script and try again, now that the password is added to Windows Credential vault.
        ::pause
        echo Restarting script...
        goto :restartPoint
        exit /b
    )
    if [!thisErr!]==[nolongeravailable] (
        echo This resource no longer exists. Skipping this drive.
    )
    if [!thisErr!]==[notexists] (
        echo This resource does not exist. Skipping this drive.
    )
    if [!thisErr!]==[alreadyused] (
        echo This drive letter is already in use. Skipping this drive.
    )
)

相关问题