1

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

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

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

我怎样才能做到这一点?

4

1 回答 1

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.
    )
)

)

于 2013-08-13T18:38:32.157 回答