Change mapped drive path via command line/batch file - windows

How do I change the path of a mapped drive via batch file?
I have written a batch file to delete files in various locations that are older than 2 weeks old.
net use Y: \\servername1\c$
cd /d Y:\Reports
SET _CmdResult=NONE
FOR /F "tokens=*" %%a IN ('forfiles -p "Y:\Reports" -s -m *.* -d -14 -c "cmd /c del #file" 2^>^&1 ^| FINDSTR ERROR') DO SET _CmdResult=%%a
IF "%_CmdResult%" == "ERROR: No files found with the specified search criteria." (
SET errorlevel=0
) ELSE (
SET errorlevel=1
)
IF "%_CmdResult%" == "NONE" SET errorlevel=0
net use Y: /delete /y
timeout 10
net use Y: \\servername2\c$
cd /d Y:\Reports
SET _CmdResult=NONE
FOR /F "tokens=*" %%a IN ('forfiles -p "Y:\Reports" -s -m *.* -d -14 -c "cmd /c del #file" 2^>^&1 ^| FINDSTR ERROR') DO SET _CmdResult=%%a
IF "%_CmdResult%" == "ERROR: No files found with the specified search criteria." (
SET errorlevel=0
) ELSE (
SET errorlevel=1
)
IF "%_CmdResult%" == "NONE" SET errorlevel=0
net use Y: /delete /y
The problem I have is that after the first instance of net use Y: /delete /y it closes the console down. Without the /y the console just waits for confirmation so never moves on.
I have tried removing the first instance of net use Y: /delete /y from the script hoping the next command net use Y: \\servername2\c$ /y would just re-assign but it errors as already in use.
I know I could map various drives at the start of the script for the specific servers but if I want to use the script to delete files from a few servers that could get messy if a drive letter is already used at some point going forward, it also seems very inefficient (more so than my script probably already is)
I also could have multiple scripts for each server location but again think it would be neater handled in 1 script.
So is there a method of changing the path of a mapped drive?

This is what I have now. It appears to be working.
I will look into the single line solution too.
I couldn't leave as comment above as there was too much text...
pushd \\servername1\c$
cd /d Reports
SET _CmdResult=NONE
FOR /F "tokens=*" %%a IN ('forfiles -p "%cd%" -s -m *.* -d -14 -c "cmd /c del #file" 2^>^&1 ^| FINDSTR ERROR') DO SET _CmdResult=%%a
IF "%_CmdResult%" == "ERROR: No files found with the specified search criteria." (
SET con1=0
) ELSE (
SET con1=1
)
IF "%_CmdResult%" == "NONE" SET con1=0
timeout 15
popd
timeout 15
pushd \\servername2\c$
cd /d Reports
SET _CmdResult=NONE
FOR /F "tokens=*" %%a IN ('forfiles -p "%cd%" -s -m *.* -d -14 -c "cmd /c del #file" 2^>^&1 ^| FINDSTR ERROR') DO SET _CmdResult=%%a
IF "%_CmdResult%" == "ERROR: No files found with the specified search criteria." (
SET con1=0
) ELSE (
SET con1=1
)
IF "%_CmdResult%" == "NONE" SET con1=0
timeout 15
popd
Thanks for all suggestions and help above

Related

How do I find if any one of the words in a file is in a very long string, which changes frequently in CMD batch

I have this filename which gets dropped into a directory on a windows share, where it needs to be located into the right location on the users' local machines, depending on if the filename has one of the keywords in it or not.
For instance:
z:\mailbox\in\Very_but#very-very!long#filenameWITH-keyword+in^it
where z: is accessible from a set of win-7 or win-10 machines. And on these machines, there are these two directories:
c:\incoming\special
c:\incoming\regular
if the filename has one of the keywords embedded in it, it needs to be copied into the c:\incoming\special folder, if not it needs to go into c:\incoming\regular folder.
my keywords are in a file, say, c:\keywords.txt
at any given time (checked every 5 minutes) there may be no files, or only one file in the z:\mailbox\in directory.
so, this is what I come up for, which is not working: (the batch file assumes there is a file to process, I haven't figured what to do, if there isn't one, yet)
dir /b z:\mailbox\in > tmp.out
set /p file=<tmp.out
del tmp.out
set keyword_found_flag=0
for /F "tokens=*" %%keyword in (c:\keywords.txt) do (
echo %file% | find /i "%%keyword"
if errorlevel=0 set keyword_found_flag=1
)
The errorlevel is always zero regardless if the keyword is found or not
IF keyword_found_flag=1 (
copy z:\mailbox\in\%file% c:\incoming\special
) ELSE (
copy z:\mailbox\in\%file% c:\incoming\regular
)
I am not sure what to do here. Any help is appreciated
Why not use operator (&&) to set your flag if execution is match?
echo %file% | find /i "%%keyword" >nul && set keyword_found_flag=1
You also don't need create/delete tmp.out file for your process, use double for to for the file name in z:\mailbox\in and, and use another for to check file contains in c:\keywords.txt with file names in z:\mailbox\in...
#echo off
set "keyword_found_flag=" && for /f tokens^=* %%i in ('dir /on /b /a:-d "z:\mailbox\in\*.*"
')do for /F tokens^=* %%K in ('type c:\keywords.txt')do echo="%%~i"| find /i "%%~K" && (
set "keyword_found_flag=1") || (set "keyword_found_flag=0")
Or...
#echo off
set "keyword_found_flag=" && for /f tokens^=* %%i in ('dir /on /b /a: -d "z:\mailbox\in\*.*"
')do for /F tokens^=* %%K in ('type c:\keywords.txt')do echo="%%~i"|find /i "%%~K" >nul && (
set "keyword_found_flag=1" && copy /v "%%~dpnxi" "c:\incoming\special\" ) || (
set "keyword_found_flag=0" && copy /v "%%~dpnxi" "c:\incoming\regular\" )

If statement for ForFiles based on file date

I have a batch file that I call via SQL server agent.
Currently I have:
ForFiles /p "C:\folder\subfolder" /d -7 /c "cmd /c del #file"
The command works fine if there is a file older than 7days.
If there isn't a file that meets the criteria then the script fails causing SQL to report failure.
Ideally I need to add and if statement that if a file exists that is older than 7 days then carry out the delete command otherwise ignore it.
Any guidance?
Wrap it inside a FOR /F command an redirect standard error to NUL.
FOR /F "delims=" %%G IN ('forfiles /P "C:\folder\subfolder" /d -7 2^>nul') do DEL "%%~G"
Try this:
cd /d C:\folder\subfolder
SET _CmdResult=NONE
FOR /F "tokens=*" %%a IN ('forfiles -p "C:\folder\subfolder" -s -m *.* -d -7 -c "cmd /c del #file" 2^>^&1 ^| FINDSTR ERROR') DO SET _CmdResult=%%a
IF "%_CmdResult%" == "ERROR: No files found with the specified search criteria." (
SET errorlevel=0
) ELSE (
SET errorlevel=1
)
IF "%_CmdResult%" == "NONE" SET errorlevel=0
it checks for an error, and will put the error into a variable and then we set the errorlevel to zero if found.

windows server 2008 r2 7z backup script

I am trying to get this script to backup a specific folder/files and zip them, then move the zip to a diff folder.
but i keep getting an error.
#ECHO off
SETLOCAL
ECHO + Setting up environment variables.
SET BACKPATH=%ThisService_RootDirectory%temp\
SET ARCPATH=C:\Program Files\7-Zip\7z.exe
SET ARCPARAMS=a -y
SET DAYSTOKEEP=3
SET ARCHIVE_DAYSTOKEEP=30
SET SOURCEPATH=%ThisService_RootDirectory%MPMissions
SET DEST_PATH=%ThisService_RootDirectory%Backups
SET BACKUP_DEST=%date:~-7,2%-%date:~4,2%-%date:~-4,4%
IF NOT EXIST "%BACKPATH%" (
ECHO ! Backup Path not found, exiting.
GOTO END
) ELSE (
ECHO * Backup Path Found.
)
IF NOT EXIST "%ARCPATH%" (
ECHO ! Archiver not found, exiting.
GOTO END
) ELSE (
ECHO * Archiver Found.
)
ECHO * Copying Files...
xcopy "%SOURCEPATH%\Documents" "%BACKPATH%\%BACKUP_DEST%\MPMissions" /v /e /s /i /y 1>NUL 2>NUL
ECHO * Archiving files...
CD /D "%BACKPATH%"
FOR /f %%a IN ('FORFILES /P %BACKPATH% /C "cmd /c if #isdir==TRUE echo #file" /D -%DAYSTOKEEP%') DO (
IF NOT EXIST %%a.7z (
"%ARCPATH%" %ARCPARAMS% %%a.7z %BACKPATH%\%%a\*.* 1>NUL 2>NUL
copy %%a.7z %DEST_PATH% 1>NUL 2>NUL
del %%a.7z 1>NUL 2>NUL
)
)
ECHO * Cleaning folders older than %DAYSTOKEEP% days..
FORFILES /P %BACKPATH% /C "cmd /c if #isdir==TRUE rmdir /s /q #file" /D -%DAYSTOKEEP% 1>NUL 2>NUL
ECHO * Cleaning files older than %DAYSTOKEEP% days..
FORFILES /P %BACKPATH% /M *.7z /C "cmd /c if #isdir==FALSE del #file" /D -%DAYSTOKEEP% 1>NUL 2>NUL
ECHO * Cleaning archives files older than %ARCHIVE_DAYSTOKEEP% days..
FORFILES /P %DEST_PATH% /M *.7z /C "cmd /c if #isdir==FALSE del #file" /D -%ARCHIVE_DAYSTOKEEP% 1>NUL 2>NUL
:END
ENDLOCAL
once I run the script it gives this message:
Setting up environment variables.
Backup Path Found.
Archiver Found.
Copying Files...
Archiving files...
ERROR: No files found with the specified search criteria.
Cleaning folders older than 3 days..
Cleaning files older than 3 days..
Cleaning archives files older than 30 days..
The script has executed successfully. You may close this window.
Now the variable %ThisService_RootDirectory% is part of tcadmin which is a gaming server service, so that variable where im executing the batch script would turn that variable into an actual path of the users service
example:
%ThisService_RootDirectory%
is
C:\TCAFiles\users\admin\5\
the script copies the files to the required folder, but it does not seem to zip the files and move the zip to the required folder.
can anyone give some assistance here please.
original source is at https://community.spiceworks.com/topic/482860-batch-script-to-transfer-and-compress
It's not a direct response to your question but why reinvent the wheel ?
All you need is in 7zBackup.ps1 (a powershell script which does exactly this)

Copying a file to mapped drive not working

I am trying to connect to a network drive, copy a file and move it to another location, and log if it is successful or not. This is what I got so far:
#echo off
#setlocal enableextensions enabledelayedexpansion
if exist Transfer_logfile.txt (
ECHO Y | del Transfer_logfile.txt
)
set LogFile=_logfile.txt
set logg=^> _^&^& type _^&^&type _^>^>%LogFile%
for /F "tokens=*" %%A in (ipaddresses.txt) do (
net use \\%%A\c$\test /USER:test %logg%
echo copying files across to %%A... %logg%
COPY -f -R -Y C:\test\test.exe \\%%A\c$\test\test.exe %logg%
echo Copy completed.. %logg%
net use \\%%A\c$\test /delete /Y %logg%
)
pause
Any help on how to finish this of would be appreciated.
I am struggling to save any errors in the output. If it errors I want it to just save that it failed in output and go on to the next IP in the IP address text file.
I think, I need to wrap an if around the net use checking that the ip address pings first. However this does not work.
#echo off
#setlocal enableextensions enabledelayedexpansion
if exist Transfer_logfile.txt (
ECHO Y | del Transfer_logfile.txt
)
set LogFile=_logfile.txt
set logg=^> _^&^& type _^&^&type _^>^>%LogFile%
for /F "tokens=*" %%A in (ipaddresses.txt) do (
ping -n %%A > NUL
IF ERRORLEVEL 0 (
echo
ELSE goto :skipcopyhost1
net use \\%%A\c$\test %logg%
echo copying files across to %%A... %logg%
COPY -f -R -Y C:\test\test.exe \\%%A\c$\test\test.exe %logg%
echo Copy completed.. %logg%
net use \\%%A\c$\test /delete /Y %logg%
)
pause
Try this not tested batch code:
#echo off
if not exist ipaddresses.txt goto :EOF
setlocal
del /F Transfer_logfile.txt 2>nul
set "LogFile=Transfer_logfile.txt"
for /F %%A in (ipaddresses.txt) do (
%SystemRoot%\System32\ping.exe -n %%A >nul
if errorlevel 1 (
echo %%A is not available in network.>>%LogFile%
) else (
echo Connecting to %%A ...>>%LogFile%
%SystemRoot%\System32\net.exe use X: \\%%A\c$\test /persistent:no /Y 2>&1 >>%LogFile%
echo Copying file to %%A ...>>%LogFile%
copy /B /V /Y C:\test\test.exe X:\test.exe 2>&1 >>%LogFile%
echo Disconnecting from %%A ...>>%LogFile%
%SystemRoot%\System32\net.exe use X: /delete /Y 2>&1 >>%LogFile%
)
echo.>>%LogFile%
)
endlocal
pause
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
copy /?
del /?
for /?
goto /?
if /?
net /?
net use /?
set /?
Further read the Microsoft articles:
Using Command Redirection Operators
Testing for a Specific Error Level in Batch Files
I don't explain all the errors in your code as they are too many.

Don't understand the return code from a forfiles command embedded in a for

I'm trying to cycle through a list of users (office_id_list_%YY_MM_DD%\%%) that I have for each office (office_list.txt) and create a file when files newer that a date (%3) are found. The below code wasn't working so I decided to echo the errorlevel and found that it was always -1073741510 (working on a Windows 2003 machine). Ultimately, I'm trying to identify user home directories(organized by office) that have not been modified since a given date.
Any thoughts would be greatly appreciated.
for /f "tokens=1 delims= " %%i in (U:\sysmon\u_cleanup\office_list.txt) do (
if not exist u:\sysmon\u_cleanup\results\%%i mkdir u:\sysmon\u_cleanup\results\%%i
for /f "tokens=1 delims= " %%j in (U:\sysmon\u_cleanup\results\office_lists_%YY_MM_DD%\%%i_dir_list_%YY_MM_DD%_final.txt) do (
forfiles /P %1%%i\%%j /S /D +%3 /C "cmd /c if %errorlevel% == 0 echo ** Do not Archive - Found files modified after %3 > U:\sysmon\u_cleanup\results\%%i\%%j_%YY_MM_DD%.txt"
)
)
Add the /V:on option to cmd and use !errorlevel! instead of %errorlevel% which turns on delayed expansion.
Probably, the main problem is the part cmd /c if %errorlevel% == 0, it expands the errorlevel before any of your commands are executed.
Normally delayed expansion is the choice, but here it doesn't work(or as Joey mentioned, with /V:on), because it is in a new cmd context.
Here you could use it this way cmd /c if %%errorlevel%% == 0, so if the complete block is parsed the first time, the part is expanded to cmd /c if %errorlevel% == 0, and this is expanded a second time, when the cmd /c is executed.
And you could beautifying the code a bit
set "officePath=U:\sysmon\u_cleanup"
set "officeDatePath=%officePath%\results\office_lists_%YY_MM_DD%"
for /f "tokens=1 delims= " %%i in ("%officePath%\office_list.txt") do (
if not exist "%officePath%\results\%%i" (
mkdir "%officePath%\results\%%i"
)
for /f "tokens=1 delims= " %%j in ("%officeDatePath%\%%i_dir_list_%YY_MM_DD%_final.txt") do (
forfiles /P %1%%i\%%j /S /D +%3 /C "cmd /c if %%errorlevel%% == 0 echo ** Do not Archive - Found files modified after %3 > %officePath%\results\%%i\%%j_%YY_MM_DD%.txt"
)
)

Resources