batch-fileftp

Using %USERNAME% environment variable in Windows batch file with command-line ftp


ftp
open ftp.drivehq.com 
username
password
cd  \wwwhome\Logs\
put "C:\Users\Cody\Desktop\ISO's\mini.iso"
bye
exit

How do you use %USERNAME% instead of hard-coding Cody, when used with ftp?


Solution

  • Here is another batch file solution with code similar to code written by Martin Prikryl with three enhancements.

    1. %USERPROFILE% is used instead of C:\Users\%username% which makes this batch file solution work also on Windows XP and on machines on which the user's profile directory is not on driveĀ C: or in a different directory than C:\Users which is of course possible too.

    2. %SystemRoot%\System32\ftp.exe is used in the batch file instead of just ftp to make this batch file work also if by chance there is an ftp.* file with a file extension listed in environment variable PATHEXT in current directory or any other directory in environment variable PATH and not being the ftp executable in Windows system directory.

    3. The ISO file name is renamed before upload with including a random decimal number between 0 and 32767 as asked for with a comment.

    The command lines of enhanced batch file:

    :RandomIsoName
    set "RandomName=mini_%RANDOM%.iso"
    if exist "%USERPROFILE%\Desktop\ISO's\%RandomName%" goto RandomIsoName
    ren "%USERPROFILE%\Desktop\ISO's\mini.iso" "%RandomName%"
    
    (
    echo open hostname
    echo username
    echo password
    echo cd \wwwhome\Logs\
    echo put "%USERPROFILE%\Desktop\ISO's\%RandomName%"
    echo bye
    )>ftp.txt
    %SystemRoot%\System32\ftp.exe -s:ftp.txt