简体   繁体   中英

batch script to download a file via ftp, how can I handle the overwrite

Good day all. I've done a batch script that connects to an FTP and download a file on the same location of the .bat file. everything works fine, now, is there a way to "ask for file overwrite permissions"? I mean, if the user already have a file named in the same way, is it possible to prevent overwrite and ask him what to do? the code actually is :

@echo off
echo user MYUSERNAME> ftpcmd.dat
echo MYPASSWORD>> ftpcmd.dat
echo bin>> ftpcmd.dat
echo cd /www.website.com/>>ftpcmd.dat
echo get afile.txt>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat ftp.website.com
del ftpcmd.dat

You can use if exist "afile.txt" in advance and use choice to let the user decide what to do:

@echo off
if exist "afile.txt" (
    choice /C YN /M "Overwrite 'afile.txt'? "
) else (
    > nul ver & rem (clear `Errorlevel`)
)
if not ErrorLevel 2 (
    > "ftpcmd.dat" (
        echo user MYUSERNAME
        echo MYPASSWORD
        echo bin
        echo cd /www.website.com/
        echo get afile.txt
        echo quit
    )
    ftp -n -s:ftpcmd.dat ftp.website.com
    del "ftpcmd.dat"
)

However, since there is no -i switch in the ftp command line and the interactive prompt mode should be on as per default, I assume the ftp command would prompt the user anyway...
Corrective Update: The "interactive mode" means that the mget and mput will ask user to confirm transfer of each matching file, not matter if it exists or not. See technet.microsoft.com/en-us/library/bb490670.aspx . There are no overwrite confirmations in ftp.exe . [ Martin Prikryl ]

Use the if exist command to test, if the local file exists already before the transfer.

If it exists, ask an user for confirmation .

@echo off

if not exist afile.txt goto download

:ask
echo Overwrite?
set INPUT=
set /P INPUT=Y/N: %=%
If /I "%INPUT%"=="Y" goto download
If /I "%INPUT%"=="N" exit
echo Incorrect input
goto ask

:download
...
ftp -n -s:ftpcmd.dat ftp.website.com

Though for a long term solution, you better use PowerShell, instead of hacking this in a batch file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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