How to make a Batch File Move another File? - batch-file

I am trying to make a batch script that moves a file into a startup folder and I want to make it universal
Currently I have this but I want to make it work on any user's computer (C:\users\USERNAME)
Here is the code
#echo off
color A0
echo Startup...
echo Startup..
echo Startup.
echo Startup
echo Startup.
echo Startup..
echo DONE
echo your name is %name%
move C:%user%\Desktop\Directory 1\dile.txt C:%user%\Desktop\Directory 1\file folder 1
:end
cmd /k
The file is called dile.txt located in a folder called Directory 1 on the desktop and I want to make it move to a folder called file folder 1 inside the Directory 1 folder. Is there a way to do this while making it work on anyone's computer?

%USERNAME% can be used to grab the active user account. Try something like this. Make sure to enclose paths in quotes when folders have spaces in their names.
#echo off
color A0
echo Startup...
echo Startup..
echo Startup.
echo Startup
echo Startup.
echo Startup..
echo DONE
echo your name is %USERNAME%
move "C:\Users\%USERNAME%\Desktop\Directory 1\file.txt" "C:\Users\%USERNAME%\Desktop\Directory 1\file folder 1\"
:end
cmd /k

Just for the sake of providing something a little bit different:
#Echo Off & SetLocal EnableExtensions
Set /P "=Startup . " 0< NUL
For /L %%G In (1,1,5) Do (Set /P "=. " 0< NUL
%SystemRoot%\System32\PATHPING.EXE 127.0.0.1 -n -q 1 -p 500 1> NUL)
Echo(&Echo Your name is %UserName%
%SystemRoot%\System32\Robocopy.exe "%UserProfile%\Desktop\Directory 1" "%UserProfile%\Desktop\Directory 1\file folder 1" "dile.txt" /Mov 1> NUL 2>&1
Pause
This uses some animated text, %UserProfile%, instead of C:\Users\%UserName%, and robocopy instead of Move. Using RoboCopy, allows for the creation of your destination directory, if it does not already exist.

Related

How to print only number of files copied as a variable, while logging all the actions?

I'm writing a script on a BAT file to use when necessary, to backup a folder of an application on several computers.
This script works on Windows 7: will it also work on Windows 10?
:: Backup script with logging
#echo off
net use \\SERVER\Shared_Folder userPassword /USER:userName
set PATH=c:\WINDOWS\system32;
set SRC="C:\Program Files (x86)\ApplicationName\TargetFolder"
set DST=\\SERVER\Shared_Folder\Backups
set LOG=%DST%\Backup_LogFile.log
echo:>>%LOG%
echo Backup from computer %COMPUTERNAME% >>%LOG%
echo Starts -- %DATE% %TIME% >>%LOG%
echo Wait please: backup is running...
xcopy %SRC% %DST%\%COMPUTERNAME%\ /A /D /E /J /Y /Z>>%LOG%
echo Ends -- %DATE% %TIME% >>%LOG%
echo:>>%LOG%
My script works fine but I want a better response on terminal for the user than execute it.
The script adds correctly the actions on a log file, but I want the user can see only the number of file copied not the list of all files copied.
Here is one way to accomplish what you ask. There are other ways too. The secret here is using "for /F" and sending each result to another function. The other function will log each line to a file. It will then look for xcopy's "File(s) copied" line and pipe that to the user if it sees it.
Also... note the "goto :EOF" statements. These tell the batch interpreter to return to the caller much like any other programming language.
I hope this does what you are asking. :)
:: Backup script with logging
#echo off
net use \\SERVER\Shared_Folder userPassword /USER:userName
set SRC="C:\Program Files (x86)\ApplicationName\TargetFolder"
set DST=\\SERVER\Shared_Folder\Backups
set LOG=%DST%\Backup_LogFile.log
echo:>>%LOG%
echo Backup from computer %COMPUTERNAME% >>%LOG%
echo Starts -- %DATE% %TIME% >>%LOG%
echo Wait please: backup is running...
for /f "delims=" %%f in ('xcopy %SRC% %DST%\%COMPUTERNAME%\ /A /D /E /J /Y /Z') do call :log_items "%%f"
echo Ends -- %DATE% %TIME% >>%LOG%
echo:>>%LOG%
goto :EOF
:log_items
Set InputLine=%~1
:: Log everything
echo %InputLine%>>%LOG%
:: Check if the line coming in contains "File(s) copied" if it doesn't, return
if "%InputLine:File(s) copied=%"=="%InputLine%" goto :EOF
:: If it does, show it to the user and return
echo %InputLine%
goto :EOF
The comparison done for the files copied looks like this:
For a line with your file name: (here they match so it returns)
C:\git\ps>if "test\targetver.h" == "test\targetver.h" goto :EOF
For a line with your number of files: (here they dont match do it doesn't return)
C:\git\ps>if "205 " == "205 File(s) copied" goto :EOF

If statement in batch script isn't working?

I have a batch script which when given the input "edit", should then echo "hello" as a sort of debug and open the batch scripts file in notepad. However for some inexplicable reason the script will not respond to the if statement no matter what. How do I get it to respond to the "edit" input?
REM #ECHO OFF
cd/
cd projects\py_test
ECHO Use this batch script to lauch Python modules living in "C:\Projects\py_test\" ONLY.
ECHO.
SET /P name="Type file name with file extension .py to start or type EDIT to edit this .bat: "
REM #ECHO OFF
cmd /k IF %name%==edit GOTO EDIT
REM IF EXIST %name% py %name%
REM IF NOT EXIST %name% echo [101mERROR: The requested file could not be found. Make sure the file exists in "C:\Projects\py_test\" and that the filename includes the ".py" extension.[0m
#ECHO OFF
:EDIT
ECHO HELLO
notepad projects-py_test-dot_start.bat`
Firstly, why all the REM #ECHO OFFs? It looks ugly, especially when they are all caps.
Then, you want to run cmd /k for an if statement for no real reason? With the variable name you need to preferbly enclose the if statement variables in double quotes to eliminate possible whitespace:
#echo off
cd /d "C:\projects\py_test"
echo Use this batch script to lauch Python modules living in "C:\Projects\py_test\" ONLY.
echo/
set /p name="Type file name with file extension .py to start or type EDIT to edit this .bat: "
if defined name set "name=%name:"=%"
if /i "%name%"=="edit" goto edit
goto :EOF
:edit
echo hello
notepad echo "%~f0"
but by guessing that you simply want to launch a python script if it exists, else edit itself, then I would instead do this version without the labels. It simply checks if the name typed exists (hoping the user typed the full script with extension) else, we add the extension test in case the user typed only the name and not extension.:
#echo off
cd /d "C:\projects\py_test"
echo Use this batch script to lauch Python modules living in "C:\Projects\py_test\" ONLY.
echo/
set /p name="Type file name with file extension .py to start or type EDIT to edit this .bat: "
if defined name set "name=%name:"=%"
if /i "%name%"=="edit" notepad "%~f0"
if exist "%name%" (
python "%name%"
) else (
if exist "%name%.py" (
python "%name%.py"
) else (
echo "%name%" does not exist
)
)

Need a little tip on batch files

I'm very new to coding and iI'm having a problem that is probably trivial, but is making me pull out my hair.
I'm using a batch script to automate mounting a VHD, executing a file inside and then pause until the user presses any key, which makes the VHD get unmounted and the script exits.
This is the main batch file:
#echo off
set fileVHD=Gord
CD /D "%~dp0"
powershell -command "Start-Process mount.cmd '%~dp0%fileVHD%.vhd' -Verb runas"
timeout /t 1
for /f %%D in ('wmic volume get DriveLetter^, Label ^| find "%fileVHD%"') do set usb=%%D
CD /D %usb%
index.html
echo "!!!!!!!!!!!!!!!!!!!!Press any key to fully close this program.!!!!!!!!!!!!!!!!!!!!!!!!!"
pause
CD /D "%~dp0"
powershell -command "Start-Process unmount.cmd '%~dp0%fileVHD%.vhd' -Verb runas"
exit
This is the mount script (Not made by me):
#echo off
setlocal enabledelayedexpansion
if "%~1"=="" (
echo Usage: %~nx0 [vhd] [letter]
exit /b 1
)
set "vhdPath=%~dpnx1"
set "driveLetter=%2"
if "!driveLetter!"=="" (
echo Mounting "!vhdPath!"
) else (
echo Mounting "!vhdPath!" to "!driveLetter!":
)
REM
REM create diskpart script
REM
set "diskPartScript=%~nx0.diskpart"
echo select vdisk file="!vhdPath!">"!diskPartScript!"
echo attach vdisk>>"!diskPartScript!"
REM assign the drive letter if requested
if not "!driveLetter!"=="" (
echo select partition 1 >>"!diskPartScript!"
echo assign letter="!driveLetter!">>"!diskPartScript!"
)
REM Show script
echo.
echo Running diskpart script:
type "!diskPartScript!"
REM
REM diskpart
REM
diskpart /s "!diskPartScript!"
del /q "!diskPartScript!"
echo Done!
endlocal
When all the files are located in a system path that contains no spaces, everything works fine. But it breaks where there are spaces.
That means that somewhere in the code a path is badly defined by the lack of quotes, probably in the mount script. The trouble is that i don't fully grasp the mount script when it starts using all the "%~...." variable path names.
I had to mix in some powershell commands because for some reason the script wouldn't work unless executed as Administrator.
If someone could give some insight to a newbie, it would be greatly appreciated.
You need end quotes around your parameters when you change directory, i.e.
CD /D "%~dp0"
You can also see all of the %~ options by running 'help for' in a console window. In those scripts it's getting the path or filename from a variable.
Discovered the root of my problem.
The path from script 1 was not being passed faithfully to script 2, even using using quotes or multiquotes.
Thanks for all the input guys!

batch download images from url with for

I need to download 300 images from site.com/folder/ using the following format: 1.png, 2.png ... 300.png
Is there a way to do this inside a batch file or using the command prompt?
Wth curl like this:
curl -o "#1.png" http://example.com/folder/[1-300].png
Here is an example to download some batch codes from a file that can be created by this script if not exist, and of course you can add or modify what you want of urls in this file !
You can add your urls in the text file named Urls.txt
Firstly, the script check for the text file named Urls.txt if exist in same location where this batch is executed and read from it the urls line by line to download them !
So, if you want to change those urls to yours, just change it from the text file Urls.txt not from the batch, i mean you can create a text file and name it to Urls.txt and put what you want as urls on this file line by line of course and let the script do its job
#echo off
Mode 110,3 & color 0A
Title Download file from web using powershell and batch by Hackoo 2017
Set "List_Urls_File=Urls.txt"
If not exist "%List_Urls_File%" Call :Create_Urls_File
Setlocal enabledelayedexpansion
#For /f "delims=" %%a in ('Type "%List_Urls_File%"') do (
Set "URL=%%a"
Rem we set the Filename from the variable !url!
#for %%# in (!url!) do ( set "File=%%~xn#" )
Rem Check if the file name contains a dot "."
Rem If not we increment the counter +1 for file to be download
ECHO !File! | FIND /I ".">Nul 2>&1
If "!errorlevel!" NEQ "0" (
Set /a Count+=1
cls & echo(
echo Downloading file "File-!Count!.bat" from URL : "!URL!"
Call :BalloonTip 'information' 10 '"Downloading File-!Count!.bat"' "'Please wait... Downloading File-!Count!.bat....'" 'info' 4
Call :Download "%%a" "File-!Count!.bat"
) else (
cls & echo(
echo Downloading file "!File!" from URL : "!URL!"
Call :BalloonTip 'information' 10 '"Downloading !File!"' "'Please wait... Downloading !File!....'" 'info' 4
Call :Download "%%a" "!File!"
)
)
Explorer "%~dp0" & exit
::*********************************************************************************
:Download <url> <File>
Powershell.exe -command "(New-Object System.Net.WebClient).DownloadFile('%1','%2')"
exit /b
::*********************************************************************************
:Create_Urls_File
(
echo https://pastebin.com/raw/XvyhRzT6
echo https://pastebin.com/raw/QqnZ0MjQ
echo https://pastebin.com/raw/tHsKw15V
echo https://pastebin.com/raw/VCnTbLB6
echo https://pastebin.com/raw/3zUTrWUz
echo https://pastebin.com/raw/31auQeFz
echo https://pastebin.com/raw/xF0uXThH
echo https://pastebin.com/raw/uzsGQD1h
echo https://pastebin.com/raw/3TmVYiZJ
echo https://pastebin.com/raw/Ntc8SZLU
echo https://pastebin.com/raw/jnpRBhwn
echo https://www.virustotal.com/static/bin/vtuploader2.2.exe
echo http://devbuilds.kaspersky-labs.com/devbuilds/KVRT/latest/full/KVRT.exe
)>"%List_Urls_File%"
exit /b
::*********************************************************************************
:BalloonTip $notifyicon $time $title $text $icon $Timeout
PowerShell ^
[reflection.assembly]::loadwithpartialname('System.Windows.Forms') ^| Out-Null; ^
[reflection.assembly]::loadwithpartialname('System.Drawing') ^| Out-Null; ^
$notify = new-object system.windows.forms.notifyicon; ^
$notify.icon = [System.Drawing.SystemIcons]::%1; ^
$notify.visible = $true; ^
$notify.showballoontip(%2,%3,%4,%5); ^
Start-Sleep -s %6; ^
$notify.Dispose()
%End PowerShell%
exit /B
::*************************************************************************
Numbered-Files Downloader 1.0
Here is a complete batch script that is doing exactly what you asked for. You don't need to download any executable files, this is 100% batch script and it should works on any (recent) Windows installation.
All you need to do is to edit the _URL variable (Line 11) and replace "example.com/folder..." with the actual URL of the files you want to download. After that, you can run the script and get your files.
Note that in your URL, this string: _NUMBERS_ is a keyword-filter that will be replaced by the incremented numbers in the final download function.
All your downloaded files will be saved in the directory where this script is located. You can choose an other directory by uncommenting the _SAVE_PATH variable (Line 15).
Finally the following variables can be changed to configure the series of numbers:
_START : The file numbers starts with this value.
_STEP   : Step between each files.
_END    : The file numbers ends with this value.
Leading Zeros
Currently, the counter doesn't support leading zeros.
EX. From Picture_001.jpg to Picture_999.jpg
But otherwise it should work fine for something like this:
EX. From Picture_1.jpg to Picture_999.jpg
I will try to find some time to add this option, it shouldn't be too difficult.
Feel free to modify & enhance this script if you need!
Numbered-DL.cmd
#echo off
setlocal EnableDelayedExpansion
rem STACKOVERFLOW - QUESTION FROM:
rem https://stackoverflow.com/questions/45796990/batch-download-images-from-url-with-for
:VARIABLES
rem WHERE YOU WANT TO SAVE FILES
rem "%~dp0" is a variable for the same folder as this script, so files should be saved in the same folder.
rem If you want to save the downloaded files somewhere else, uncomment the next line and edit the path.
SET "_SAVE_DIR=%~dp0"
rem SET _SAVE_PATH=C:\Folder\
rem DOWNLOAD THIS FILE URL
rem
rem "_NUMBERS_" WILL BE REPLACED BY THE COUNTER
rem CURRENLY IT DOESN'T SUPPORT CHOOSING A NUMBERS OF ZEROS FOR THE COUNTER EX: 001,002,003...
rem BUT IT SHOULDN'T BE TOO HARD TO IMPLEMENT, MAYBE ILL ADD THIS IN THE FUTURE.
rem
rem SET _FILE_URL=https://example.com/folder/_NUMBERS_.png
SET "_FILE_URL=https://cweb.canon.jp/eos/lineup/r5/image/downloads/sample0_NUMBERS_.jpg"
rem FOR THIS EXAMPLE THE SCRIPT WILL DOWNLOAD FILES FROM "sample01.jpg" TO "sample05.jpg"
SET _START=1
SET _STEP=1
SET _END=5
:CMD_PARAMS
IF NOT [%1]==[] SET "_FILE_URL=%1"
IF NOT [%2]==[] SET "_SAVE_DIR=%2"
:PATH_FIX
rem REMOVE THE LAST CHAR IF IT IS "\"
IF [%_SAVE_DIR:~-1%] == [\] SET "_SAVE_DIR=%_SAVE_DIR:~0,-1%"
:DETAILS_DISPLAY
ECHO.
ECHO SCRIPT: Numbered-Files Downloader 1.0
ECHO AUTHOR: Frank Einstein
ECHO.
ECHO.
ECHO INPUTS
ECHO _URL: %_FILE_URL%
ECHO _SAVE_DIR: %_SAVE_DIR%
ECHO.
ECHO _START: %_START%
ECHO _STEP= %_STEP%
ECHO _END= %_END%
ECHO.
ECHO.
CALL :DOWNLOAD_LOOP
ECHO.
ECHO EXECUTION COMPLETED
ECHO.
PAUSE
EXIT /B
:DOWNLOAD_LOOP
SET FINAL_URL=%_FILE_URL%
FOR /L %%G IN (%_START%,%_STEP%,%_END%) DO (
rem REPLACE URL'S KEYWORD WITH NUMBERS
SET NUM=%%G
SET FINAL_URL=%FINAL_URL:_NUMBERS_=!NUM!%
rem CUMSTOM BATCH FUNCTION FOR DOWNLOADING FILES
rem
rem SYNTAX:
rem echo CALL :DOWNLOAD !FINAL_URL!
CALL :DOWNLOAD !FINAL_URL! !_SAVE_DIR!
)
Goto :EOF
rem PAUSE
rem EXIT /B
rem FUNCTIONS
:DOWNLOAD
setlocal
SET "DL_FILE_URL=%1"
SET "DL_SAVE_DIR=%2"
rem EXTRACT THE FILENAME FROM URL (NEED TO FIX THIS PART?)
FOR %%F IN ("%DL_FILE_URL%") DO SET DL_FILE_NAME=%%~nxF
IF "%DL_SAVE_DIR:~-1%" == "\" SET "DL_SAVE_DIR=%DL_SAVE_DIR:~0,-1%"
IF NOT [%2]==[] SET "DL_SAVE_FILE=%DL_SAVE_DIR%\%DL_FILE_NAME%"
IF [%2]==[] SET "DL_SAVE_FILE=%~dp0%DL_FILE_NAME%"
rem :BITSADMIN
ECHO.
ECHO DOWNLOADING: "%DL_FILE_URL%"
ECHO SAVING TO: "%DL_SAVE_FILE%"
ECHO.
bitsadmin /transfer mydownloadjob /download /priority foreground "%DL_FILE_URL%" "%DL_SAVE_FILE%"
rem BITSADMIN DOWNLOAD EXAMPLE
rem bitsadmin /transfer mydownloadjob /download /priority foreground http://example.com/filename.zip C:\Users\username\Downloads\filename.zip
endlocal
GOTO :EOF
try with winhttpjs.bat:
set "baseLink=http://example.org/folder/"
for /l %%a in (1;1;300) do (
winhttpjs.bat "%baseLink%%%a.png" -saveto %%a.png
)

Update a batch file from another batch file

Dear StackOverFlow Members,
Please help me with this batch file. I would like to use the answer given from the "SET /P INPUT=%=%" and have it update another batch file permanently.
This is the first batch file that runs to get an answer from the user
#echo off
cls
echo.
echo .................................................................
echo ..... Specify what the name of the Store is, this will send .....
echo ............... alerts to abd#abc.co.za ..............
echo .................................................................
echo.
pause
:option
cls
color 5E
echo.
echo "............ Press 1 to specify what the store name is......"
echo "............ Press 2 to exit the program ................."
echo.
SET /P M=Type from the menu above 1 or 2 then press ENTER:
IF %M%==1 GOTO SEND
IF %M%==2 GOTO EOF
:SEND
cls
color 0A
set INPUT=
set /P INPUT=Enter Store Name: %=%
if "%INPUT%"=="" goto input
echo "You said that the store name is: %INPUT%"
:: Have the user confirm his/her choice
SET /P ANSWER=Is the name correct (Y/N)?
echo You chose: %ANSWER%
if /i {%ANSWER%}=={y} (goto :yes)
if /i {%ANSWER%}=={yes} (goto :yes)
goto :no
:yes
echo You pressed YES!... The name is updating
goto name
:no
echo You pressed NO!... The program will exit
pause
cls
goto eof
:name
::set /A store=%INPUT%
echo %INPUT% >> notify_support.bat
::Terminate the program
:EOF
As you can see I am struggling to specify where I should "echo %INPUT% >> notify_support.bat". This is code taken from the second batch file
#echo off
call senditquiet -s smtp.gmail.com -port 587 -u rsupp0rt#gmail.com -protocol ssl -p access -f rsupp0rt#gmail.com -t 888#gmail.com -subject "Store ABC" -body "Hello there, There is an issue logged at the store.<br>Best regards."
When the first batch file runs, it updates the second one but just dumps it at the end of the file.
I need the INPUT ECHOed to replace "Store ABC" in the second batch file.
Please assist, I'm rather rusty with batch files.
echo %INPUT% >> notify_support.bat
That line contains >> which means 'dump at the end of the file'. You can use a single > to overwrite the existing file contents. That way, you can re-generate the whole file (which is only 2 lines anyway).
A different solution is to actually parse the exising file and replace that text. You can do that by using for /F ..., which allows you to traverse through the lines of a file. You can then generate a new file, based on the (altered) contents of the existing file. Disadvantage is that this file-parsing method is especially suitable for data files in which each line has the same format with fields and delimiters (like a CSV file). It is less suited for parsing 'complex' files like a batch file or program source file.
try the code:
#echo off
echo Welcome
echo > echo #echo off >> batchfilename.bat
echo > echo echo hello >> batchfilename.bat
echo > echo pause >> batchfilename.bat
it will input the code into the batch file and when you run batchfilename.bat you will get something like:
hello
press any key to continue . . .

Resources