Determining OS version via Scripting - batch-file

I found this script on another site but I can not get it to work and I don't know batch scripting that well
Set objWshShell = WScript.CreateObject("WScript.Shell")
strOSVersion = objWshShell.RegRead("HKLM\Software\Microsoft\Windows NT\CurrentVersion\CurrentVersion")
If strOSVersion = "5.1" Then
Debug.WriteLine("Windows XP")
Rem Insert Windows XP Statements
ElseIf strOSVersion = "6.0" Then
Debug.WriteLine("Windows Vista")
Rem Insert Windows Vista Statements
ElseIf strOSVersion = "6.1" Then
Debug.WriteLine("Windows 7")
Rem Insert Windows 7 Statements
End If
now if I run this I get the error on the second line
'strOSVersion' is not recognized as an internal or external command
operable program or batch file.
= was unexpected at this time.
I do not know why

It's a VB script. You can save in a file named like test.vbs
Then open a command prompt, change directory to where you saved the file. At the prompt type cscript test.vbs.
Before that, I changed the Debug.WriteLine calls to WScript.Echo instead.

This is a Batch Script (.bat) that I've put together and use often for determining OS.
#ECHO OFF
SetLocal
REM --------> EDIT BELOW <--------
REM Edit below if you would like to audit the pc's you run this on and store the information in a file, either T or F (for True or False)
set storeValue=T
REM Edit below the location on a network drive that you can write to
set sharePath=\\servername\sharepath
REM -----> DO NOT EDIT BELOW <-----
IF NOT EXIST C:\Temp MD C:\Temp
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" | findstr ProductName>C:\temp\osver.txt
set osver=
set tempLoc=C:\Temp
FOR /F "tokens=3* delims= " %%I IN (%tempLoc%\OSver.txt) DO SET osVer=%%I %%J
echo.-----------------------------------------
echo. You are running: %osVer%
echo.-----------------------------------------
IF '%storeValue%'=='F' goto end
IF '%storeValue%'=='T' goto storeValue
:storeValue
ipconfig |findstr IPv4>c:\temp\ipadd.txt
REM FOR /F "tokens=12* delims=." %%A IN (%tempLoc%\IPAdd.txt) DO SET IPAdd=%%A.%%B
FOR /F "tokens=2* delims=:" %%A IN (%tempLoc%\IPAdd.txt) DO SET IPAdd=%%A
IF EXIST %sharePath%\PC_Audit_List.txt goto audit
echo.PC Audit List>%sharePath%\PC_Audit_List.txt
echo.------------------------------------------------------------->>%sharePath%\PC_Audit_List.txt
goto audit
:audit
echo.%computername% - %IPAdd% - %osVer%>>%sharePath%\PC_Audit_List.txt
goto end
:end
IF EXIST %tempLoc%\OSver.txt del %tempLoc%\OSver.txt /f /q
IF EXIST %tempLoc%\IPAdd.txt del %tempLoc%\IPAdd.txt /f /q
EndLocal
pause
exit
I'm sure this will suit your needs, I've included an option for you to write the IP, Name and then the Version into a file.

#echo off
setlocal EnableDelayedExpansion
::Identify OS
for /F "delims=" %%a in ('ver') do set ver=%%a
set Version=
for %%a in (95=95 98=98 ME=ME NT=NT 2000=2000 5.1.=XP 5.2.=2003 6.0.=Vista 6.1.=7 6.2.=8 6.3=8.1) do (
if "!Version!" equ "this" (
set Version=Windows %%a
) else if "!ver: %%a=!" neq "%ver%" (
set Version=this
)
)
::Identify bit
if exist "%SYSTEMDRIVE%\Program Files (x86)" (
set Type=64 bit
) else (
set Type=32 bit
)
::Display result
echo %Version% %Type%
echo/
pause
Copied from: http://www.dostips.com/forum/viewtopic.php?f=3&t=4387

Related

batch to display folders to select from, user selects folder, then it copies that folder to another folder

So what I'm trying to do is, i have a bat file that makes timestamped backups(for example, 180126_053327 in the format: yymmdd_hhmmss). I'm trying to create this bat to add to it, so i can have it lookup those backups, display in console to allow the user to select the backup they want to restore by inputting the number they want and then copy it to a location.
so far what i have creates this:
Pic of what I have so far
The pic above is from the following script:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
set i=0
For /f %%a in ('dir I:\AM_Configs-backups\ /B /A /D') do (
set /a i+=1
echo !i! %%a
set dir!i!=%%a
)
echo.
set /p uin="Select a directory [1-!i!]: "
set udir=!dir%uin%!
echo Selected - %udir%
md c:\test2
copy %udir% c:\test2
#PAUSE
I keep getting this:
Select a directory [1-29]: 27
Selected - 180126_053327
The system cannot find the file specified.
Press any key to continue . . .
I got the script above from this link: Prompting user to select directory in batch file
It cannot be found because %udir% is not in the current directory. This means that your base directory, I:\AM_Configs-backups, needs to be pre-fixed to your Copy command.
Copy "I:\AM_Configs-backups\%udir%" "C:\test2"
Also here is an alternative to the linked example you provided in your question:
#Echo Off
SetLocal EnableDelayedExpansion
Set "baseDir=I:\AM_Configs-backups"
For /F "Delims==" %%A In ('"(Set dir[) 2>Nul"') Do Set "%%A="
Set "i=0"
For /D %%A In ("%baseDir%\*") Do (Set /A i+=1 & Set "dir[!i!]=%%~nxA")
If %i% Equ 1 (Set "dir[X]=%baseDir%\%dir[1]%") Else Call :Menu
Rem Your commands using the selected directory begin below
Echo you selected %dir[X]%
If Not Exist "C:\test2\" MD "C:\test2"
Copy "%dir[X]%" "C:\test2"
Pause
Exit /B
:Menu
For /L %%A In (1,1,%i%) Do (Echo %%A. !dir[%%A]!)
Set /P "dir[X]=Select a directory from the above list: "
If Not Defined dir[%dir[X]%] (ClS & GoTo Menu)
Set "dir[X]=%baseDir%\!dir[%dir[X]%]!"
You can adjust your base directory on line 3 and put your own commands from line 9 onwards, (up to the Exit /B).
You should consider using RoboCopy for copying directories!
Edit
For the XCopy version, you'd probably need to change to:
#Echo Off
SetLocal EnableDelayedExpansion
Set "baseDir=I:\AM_Configs-backups"
For /F "Delims==" %%A In ('"(Set dir[) 2>Nul"') Do Set "%%A="
Set "i=0"
For /D %%A In ("%baseDir%\*") Do (Set /A i+=1 & Set "dir[!i!]=%%~nxA")
If %i% Equ 1 (Set "dir[X]=%dir[1]%") Else Call :Menu
Rem Your commands using the selected directory begin below
Echo you selected %dir[X]%
XCopy "%baseDir%\%dir[X]%" "%AppData%\Awesomeminer\%dir[X]%" /S /I /F /Y 2>Nul
Echo Starting Awesome Miner...
Start "" "%ProgramFiles(x86)%\Awesome Miner\AwesomeMiner.exe"
Pause
Call "Switch-N-Bkup.bat"
Pause
Exit /B
:Menu
For /L %%A In (1,1,%i%) Do (Echo %%A. !dir[%%A]!)
Set /P "dir[X]=Select a directory from the above list: "
If Not Defined dir[%dir[X]%] (ClS & GoTo Menu)
Set "dir[X]=!dir[%dir[X]%]!"
For the RoboCopy version you'd change line 11 to:
RoboCopy "%baseDir%\%dir[X]%" "C:\test2\%dir[X]%" /S 2>Nul
...plus any additional switches you may need
I ended up using this cus i have another batch for switching and backing up:
to kinda give you an idea, i have a primary bat for switching and copying configs, which will start teh program automatically after their copied. in that bat i also have code for backing up current configs to a location using time/date and creates the folders in this format: yymmdd_hhmmss...i needed an easy restore function, which with the link and code you provided helped with the user able to select which folder to restore and copying it to the programs data folder to be used, then auto-starting the program using the copied config.
#Echo Off
SetLocal EnableDelayedExpansion
Set "baseDir=I:\AM_Configs-backups"
For /F "Delims==" %%A In ('"(Set dir[) 2>Nul"') Do Set "%%A="
Set "i=0"
For /D %%A In ("%baseDir%\*") Do (Set /A i+=1 & Set "dir[!i!]=%%~nxA")
If %i% Equ 1 (Set "dir[X]=%baseDir%\%dir[1]%") Else Call :Menu
Rem Your commands using the selected directory begin below
Echo you selected %dir[X]%
REM If Not Exist "C:\test2\" MD "C:\test2"
xcopy "%dir[X]%" "%USERPROFILE%\AppData\Roaming\Awesomeminer\" /S /F /R /Y
START C:\"Program Files (x86)"\"Awesome Miner"\AwesomeMiner.exe
ECHO Starting Awesome Miner...
#Pause
CALL Switch-N-Bkup.bat
exit /b
:Menu
For /L %%A In (1,1,%i%) Do (Echo %%A. !dir[%%A]!)
Set /P "dir[X]=Select a directory from the above list: "
If Not Defined dir[%dir[X]%] (ClS & GoTo Menu)
Set "dir[X]=%baseDir%\!dir[%dir[X]%]!"

Compare file name substring with folder name substring and move

I need to move few files from one folder to sub folder. My folder structure is already ready.
File current folder: D:\AB\*.*
The file name is: SS-AA-Report-Temp File for Script Testing-Daily-31March.txt
Destination folder: D:\AB\Pm 1.1 File For Script\Daily\
How to check file name substring with folder name substring and move?
Note I have multiple files like this.
set Path1= d:\AB
Pushd %Path1%
echo %Path1%
for %%i in (*.*) do SET "FName=%%~ni"
For /F "Tokens=4-5 Delims=-" %%A In ("%FName%") Do (
Set "FoldOne=%%A"
Set "FoldTwo=%%B"
)
echo out %RDate%
mkdir %Path1%\"%FoldOne%"\"%FoldTwo%"\%RDate%
move %Path1%\"%FName%".* %Path1%\"%FoldOne%"\"%FoldTwo%"\%RDate%\
Edit:
File names format:
A-A-Format-Here First connectivity install on Day 0 regurlarly-Daily-All-2017-03-27-09-31-16.xls
A-A-Format-Already First connectivity with 10 days created-Weekly-All-2016-11-28-10-01-02.csv
A-A-Report-withname 1.2 Sample Report (Network Plan Report)-Daily-Detail-2017-01-03-23-53.xls
A-A-Report-Nextreport 1.2 Sample Report (Network Plan Report)-Weekly-Detail-2017-01-03-23-02-53.csv
Now my folder structure is:
D:\AB\Pm 1.1 First connectivity install on Day 0\Daily\05042017
D:\AB\Pm 2.1 First connectivity with 10 days\Weekly\29032017
D:\AB\Pm 1.2 Sample Report\Daily\05042017
D:\AB\Pm 1.2 Sample Report\Weekly\29032017
And here is the batch file I have already:
set Path1= d:\AB
Pushd %Path1%
echo %Path1%
for %%i in (*.*) do SET "FName=%%~ni"
For /F "Tokens=4-5 Delims=-" %%A In ("%FName%") Do (
Set "FoldOne=%%A"
Set "FoldTwo=%%B"
)
echo 1 %FoldOne%
echo 3 %FoldTwo%
IF %FoldTwo% == Daily (
echo here Daily
For /F UseBackQ %%A In (
`PowerShell "(Get-Date).AddDays(-1).ToString('ddMMyyyy')"`
) Do (Set "RDate=%%A"
echo ffor %RDate%
)
)
IF %FoldTwo% == Weekly (
Echo Weekly
For /F UseBackQ %%A In (
`PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')"`
) Do (Set "RDate=%%A"
echo %RDate%
)
)
mkdir %Path1%\"%FoldOne%"\"%FoldTwo%"\%RDate%
move %Path1%\"%FName%".* %Path1%\"%FoldOne%"\"%FoldTwo%"\%RDate%\
Pushd d:\
GoTo :EOF
The logic for matching file name substrings with folder name is still very fuzzy.
However, I coded two possible solutions doing both the same using partly different methods.
The first complete batch code:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
cd /D "D:\AB"
rem Get name of each subfolder starting with string Pm, a space, two single
rem digit numbers separated by a dot, one more space and more characters to
rem indexed environment variables for later usage. And assign the substring
rem after the first 7 characters of each folder name also to an index
rem environment variable.
set FolderIndex=0
for /D %%I in ("Pm ?.? *") do (
set "FolderName!FolderIndex!=%%I"
set "CurrentPath=%%I
set "FolderPart!FolderIndex!=!CurrentPath:~7!"
set /A FolderIndex+=1
)
set "FolderCount=%FolderIndex%"
rem set Folder
rem Get date of yesterday and date of a week ago.
for /F "usebackq" %%I in (`PowerShell.exe "(Get-Date).AddDays(-1).ToString('ddMMyyyy')"`) do set "DateDaily=%%I"
for /F "usebackq" %%I in (`PowerShell.exe "(Get-Date).AddDays(-7).ToString('ddMMyyyy')"`) do set "DateWeekly=%%I"
rem set Date
rem Process now each file matching the wildcard pattern below in
rem current folder and calling a subroutine with current file name.
set "FileNotMoved=0"
for %%I in (*-*-*-*-*) do call :MoveToFolder "%%I"
endlocal & if not %FileNotMoved% == 0 pause
goto :EOF
rem This subroutine first gets fourth and fifth dash delimited part from
rem each passed double quoted file name.
rem Then it replaces in each fourth file name part each folder name part
rem by an empty string until either all folder name parts are processed
rem or the string substitution was successful meaning the file name part
rem really contains the folder name part.
rem Note: The substitution does not work correct if any folder name part
rem contains an equal sign as this character is the delimiter
rem between string to find and replace string for substitution.
rem In second case with substitution being successful the folder for
rem the file could be determined and the file is moved to the found
rem folder if also time part could be determined from file name.
:MoveToFolder
for /F "tokens=4,5 delims=-" %%A in ("%~1") do set "NamePart=%%A" & set "NameTime=%%B"
set "FolderIndex=0"
:FindFolder
if %FolderIndex% == %FolderCount% (
set "FileNotMoved=1"
echo Found no folder for: %1
goto :EOF
)
call set "CurrentPart=%%FolderPart%FolderIndex%%%"
if "!NamePart:%CurrentPart%=!" == "!NamePart!" (
set /A FolderIndex+=1
goto FindFolder
)
call set "CurrentFolder=%%FolderName%FolderIndex%%%"
if /I "%NameTime%" == "Daily" (
set "FolderTime=%DateDaily%"
) else if /I "%NameTime%" == "Weekly" (
set "FolderTime=%DateWeekly%"
) else (
set "FileNotMoved=1"
echo Undefined time for: %1
goto :EOF
)
mkdir "%CurrentFolder%\%NameTime%\%FolderTime%" 2>nul
move "%~1" "%CurrentFolder%\%NameTime%\%FolderTime%\" >nul
if errorlevel 1 (
set "FileNotMoved=1"
echo Failed to move file: %1
)
goto :EOF
The second batch code differs from first solution only on how subroutine MoveToFolder is coded for finding the corresponding folder for current file name. For that reason just the code of the subroutine is posted below.
:MoveToFolder
for /F "tokens=4,5 delims=-" %%A in ("%~1") do set "NamePart=%%A" & set "NameTime=%%B"
for /F "tokens=1* delims==" %%X in ('set FolderPart') do (
if not "!NamePart:%%Y=!" == "%NamePart%" (
set "FolderName=%%X"
goto FoundFolder
)
)
set "FileNotMoved=1"
echo Found no folder for: %1
goto :EOF
:FoundFolder
if /I "%NameTime%" == "Daily" (
set "FolderTime=%DateDaily%"
) else if /I "%NameTime%" == "Weekly" (
set "FolderTime=%DateWeekly%"
) else (
set "FileNotMoved=1"
echo Undefined time for: %1
goto :EOF
)
set "FolderIndex=%FolderName:~10%"
call set "CurrentFolder=%%FolderName%FolderIndex%%%"
mkdir "%CurrentFolder%\%NameTime%\%FolderTime%" 2>nul
move %1 "%CurrentFolder%\%NameTime%\%FolderTime%\" >nul
if errorlevel 1 (
set "FileNotMoved=1"
echo Failed to move file: %1
)
goto :EOF
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.
call /?
cd /?
echo /?
endlocal /?
for /?
goto /?
if /?
mkdir /?
move /?
pause /?
rem /?
set /?
setlocal /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul and >nul and answer on question Single line with multiple commands using Windows batch file for meaning of operator & on Windows command lines.

Search file with wildcard path

I want to write a script to prompt user for file path and list all files found. The file path can contain wildcards. Something similar to this. But the batch script version of it. For example:
C:\Somewhere\user*\app\version-*.*\start.exe
The files might be located like this:
C:\Somewhere\user345\app\version-1.0\start.exe
C:\Somewhere\user898\app\version-1.2\start.exe
C:\Somewhere\user898\app\version-1.3\start.exe
I tried to use FOR and it turns out to be so much harder than expected because FOR does not support wildcards in the middle of a path.
Is there a way to list these files? (Maybe without using for?)
I think this recursive solution works pretty well; you may name it WCDIR.bat:
#echo off
setlocal
if "%~1" neq "" set "next=%~1" & goto next
echo Show files selected by several wild-cards
echo/
echo WCDIR wildcardPath
echo/
echo Each folder in the path may contain wild-cards
echo the last part must be a file wild-card
goto :EOF
:next
for /F "tokens=1* delims=\" %%a in ("%next%") do set "this=%%a" & set "next=%%b"
if defined next (
for /D %%a in ("%this::=:\%") do (
setlocal
cd /D "%%~a" 2>NUL
if not errorlevel 1 call :next
endlocal
)
) else (
for /F "delims=" %%a in ('dir /B /A:-D "%this%" 2^>NUL') do echo %%~Fa
)
exit /B
EDIT: I fixed a small bug in the last for /F command.
For example, the output of WCDIR.bat C:\Windows\Sys*\find*.exe command in my Windows 8.1 64-bits computer is:
C:\Windows\System32\find.exe
C:\Windows\System32\findstr.exe
C:\Windows\SysWOW64\find.exe
C:\Windows\SysWOW64\findstr.exe
You can try with the command Where /?
The WHERE command is roughly equivalent to the UNIX 'which' command. By default, the search is done in the current directory and in the PATH.
#echo off
Where /R "%programfiles%" *winrar.exe
pause
#echo off
:: Example d'input
set UserInput=*drive*
:: building the Pattern
set cmd=%Userinput%.exe
:: storage Where.exe command in a macro, the execution will be faster
set whereCmd=where.exe /r c:\windows\ %cmd%
:: execution of macro and output formatting
for /f %%a in ('%whereCmd%') do echo %%~nxa --^> %%a
pause

Batch Function can't write to log variable

I have a batch script that goes into a folder's subfolders (excluding one folder) gets .log files, archives them, and then deletes the originals.
Folder structure:
\Logs\logs1
\Logs\logs2
\Logs\logs3
Originally, I had this loop as just one line, which worked and looked like this:
FOR /F "usebackq tokens=* delims=" %%A IN (`DIR "%LogsFilespec%" /B /S ^|find ^"logs3^" /v `) DO %zipCommand% >> %ProcessLog% & DEL "%%~fA" & ECHO Deleting "%%~fA" >> %ProcessLog% & ECHO. >> %ProcessLog%
But, I was instructed to turn it into a simpler-looking FOR DO CALL, and as a result I am stuck, unsure of whats wrong. %targetDate% is YYYYMMDD.
**Edited for fuller code trying rojo's suggestion:
SET ProcessLog=C:\Users\Me\Documents\batch_files\%~n0_%jobLog%.txt
:DetermineArchiveApp
:: Create specifics for ITD Logs collection
SET ITDLogsLocation=C:\Users\Me\Documents\fakeG
SET ITDLogsName=trace*%targetDate%.log
SET ITDLogsFilespec=%ITDLogsLocation%\%ITDLogsName%
:: ********************************************************************************
:: * Check if server has WinZip or 7-Zip installed. setup environment variable *
:: * accordingly with executable path and name, and with any required parameters. *
:: ********************************************************************************
SET PathWinZip="C:\Program Files\WinZip\wzzip.exe"
SET Path7Zip_64bit="C:\Program Files\7-Zip\7z.exe"
SET Path7Zip_32bit="C:\Program Files (x86)\7-Zip\7z.exe"
SET Path7Zip_true="C:\Users\Me\Documents\batch_files\7za.exe"
:: Check for 32-bit version of 7-Zip. If found, configure
:: its command line parameter to produce a .zip file
IF EXIST %Path7Zip_32bit% SET zipCommand=%Path7Zip_32bit% a
::Check for WinZip
IF EXIST %PathWinZip% SET zipCommand=%PathWinZip% -a
:: Check for 64-bit version of 7-Zip. If found, configure
:: its command line parameter to produce a .zip file
IF EXIST %Path7Zip_64bit% SET zipCommand=%Path7Zip_64bit% a
:: Check for 64-bit version of 7-Zip. If found, configure
:: its command line parameter to produce a .zip file
IF EXIST %Path7Zip_true% SET zipCommand=%Path7Zip_true% a
:ArchiveProcess
ECHO ***************************************************** >> %ProcessLog%
::Write the date and time of job starting to a log
ECHO %DATE% %TIME% START >> %ProcessLog%
::Loop through the list that DIR gives for the given folder, and for each folder do zipCommand, excluding ITD\Data\AFS, and write to log
FOR /F "delims=" %%A IN (
'DIR "%LogsFilespec%" /B /S ^|find /v "logs3"'
) DO CALL :DoZip "%%~dpnA" "%%~fA" "%zipCommand%" "%ProcessLog%"
::Write end to log
ECHO %DATE% %TIME% %~nx0 END >> %ProcessLog%
ECHO ***************************************************** >> %ProcessLog%
:DoZip
setlocal
SET "archiveName=%~1"
SET "SourceFileSpec=%~2"
SET "zipCommand=%~3"
SET "RunLog=%~4"
>>"%RunLog%" (
echo Archiving %SourceFileSpec%...
"%zipCommand%" "%archiveName%.zip" "%SourceFileSpec%"
echo %TIME% Deleting %SourceFileSpec%...
DEL "%SourceFileSpec%"
echo;
)
GOTO :EOF
The errors I get from the cmd NOW are:
'""' is not recognized as an internal or external command, operable program or batch file.
Whats wrong with the syntax of either!?
EDIT 2: Heading home now, cant work remotely yet so I'll be back at it tommorow.
The current issue is that: the 7zip command line does not like
"C:\Users\Me\Documents\batch_files\7za.exe" a
and also the >>"%RunLog%" block doesn't work, if comment out just the archival and deletion lines to see what's happening, I just get thrown
The system cannot find the drive specified.
The system cannot find the drive specified.
The system cannot find the drive specified.
The system cannot find the drive specified.
The system cannot find the path specified.
The biggest difference I see is that in your successful one-liner, you have stuff properly quoted; whereas in your call both in the caller and the subroutine, you quote nothing. If any of your paths include spaces or special characters, calamity ensues. Try this:
FOR /F "delims=" %%A IN (
'DIR "%LogsFilespec%" /B /S ^|find /v "logs3"'
) DO CALL :DoZip "%%~dpnA" "%%~fA" "%zipCommand%" "%ProcessLog%"
...
:DoZip <basename> <fqpath> <zipcmd> <log>
setlocal
SET "archiveName=%~1"
SET "SourceFileSpec=%~2"
SET "zipCommand=%~3"
SET "RunLog=%~4"
>>"%RunLog%" (
echo Archiving %SourceFileSpec%...
"%zipCommand%" "%archiveName%.zip" "%SourceFileSpec%"
echo %TIME% Deleting %SourceFileSpec%...
DEL "%SourceFileSpec%"
echo;
)
GOTO :EOF
By the way, did you know you could zip without 3rd party software?
This whole ordeal is turning into a mess. I hope you'll allow me to offer some general scripting advice and receive it as benevolence rather than criticism.
Whenever you set a variable to a string in batch scripting, it helps to set "var=value" with the var=value pair quoted. When you need your variable to be evaluated within quotes, call it as "%var%". This removes any ambiguity about your intentions, and saves you from having to remember which variable values you've quoted and which you haven't.
To directly address your most recent problem, I suggest either adding a 5th argument to your call for "a|-a" (for 7za or wzzip), or determine within the loop whether you should use a or -a based on whether the archiver is 7za or wzzip.
Try this:
#echo off
setlocal
SET "ProcessLog=%USERPROFILE%\Documents\batch_files\%~n0_%jobLog%.txt"
:DetermineArchiveApp
:: Create specifics for ITD Logs collection
SET "ITDLogsLocation=%USERPROFILE%\Documents\fakeG"
SET "ITDLogsName=trace*%targetDate%.log"
SET "ITDLogsFilespec=%ITDLogsLocation%\%ITDLogsName%"
:: ********************************************************************************
:: * Check if server has WinZip or 7-Zip installed. setup environment variable *
:: * accordingly with executable path and name, and with any required parameters. *
:: ********************************************************************************
for %%I in ("%PROGRAMFILES%" "%PROGRAMFILES(x86)%") do (
for %%z in ("%%~I\WinZip\wzzip.exe" "%%~I\7-Zip\7z.exe") do (
if exist "%%~z" set "zipCommand=%%~z"
)
)
if not defined zipCommand set "zipCommand=%USERPROFILE%\Documents\batch_files\7za.exe"
if not exist "%zipCommand%" (
echo Unable to locate 7z.exe, 7za.exe, or wzzip.exe
exit /b 1
)
:ArchiveProcess
::Write the date and time of job starting to a log
>> "%ProcessLog%" (
ECHO *****************************************************
ECHO %DATE% %TIME% START
)
::Loop through the list that DIR gives for the given folder, and for each folder do zipCommand, excluding ITD\Data\AFS, and write to log
FOR /F "delims=" %%A IN (
'DIR "%ITDLogsFilespec%" /B /S ^| find /v "logs3"'
) DO CALL :DoZip "%%~dpnA" "%%~fA" "%zipCommand%" "%ProcessLog%"
::Write end to log
>> "%ProcessLog%" (
ECHO %DATE% %TIME% %~nx0 END
ECHO *****************************************************
)
::End main runtime
goto :EOF
:DoZip
setlocal
SET "archiveName=%~1"
SET "SourceFileSpec=%~2"
SET "zipCommand=%~3"
SET "RunLog=%~4"
if "%zipCommand%"=="%zipCommand:7z=%" (
rem then this is WinZip.
set "switch=-a"
) else set "switch=a"
>>"%RunLog%" (
echo Archiving %SourceFileSpec%...
"%zipCommand%" %switch% "%archiveName%.zip" "%SourceFileSpec%"
echo %TIME% Deleting %SourceFileSpec%...
DEL "%SourceFileSpec%"
echo;
)
GOTO :EOF

batch-file incorporate another batch that copies modified files in directory to another directory

Here is what I've come up with, however I can't get the correct reference of xcopy in my code from what Aacini has provided in another post. cmd console will say it cannot find file "!lastName!!baseExt!" and then show that 0 files have been copied. It's not copying because I think the xcopy syntax will not allow for substitutions for the "source" "directory" relationship following xcopy.
Any help would be much appreciated. Thanks
#Echo Off
:: variables
set drive=C:\Users\me\Desktop\Test Source Folder
set backupcmd=xcopy /m /s /c /d /e /h /i /r /y /exclude:AutoFileCopy_Rev1.bat
set basename=
for %%a in ("C:\Users\me\Desktop\Test Source Folder") do (
if not defined baseName (
rem Is first name of first set
set baseName=%%~Na
set baseExt=%%~Xa
set lastname=%%~Na
) else (
rem Check if this name begin with same baseName
set name=%%~Na
for %%b in (!baseName!) do set name=!name:*%%b=!
if "!name!" neq "%%~Na" (
rem Yes: Is next name of same set
set lastName=%%~Na
) else (
rem No: Is first name of next set: copy previous set and pass to next one
%backupcmd% "!lastName!!baseExt!" "C:\Users\me\Desktop\Test Source Folder\! baseName!!baseExt!"
set baseName=%%~Na
set baseExt=%%~Xa
set lastName=%%~Na
)
)
)
rem Copy last set
Set _Delay=10
Set _Monitor=C:\Users\me\Desktop\Test Source Folder\
Set _Base=%temp%\BaselineState.dir
Set _Chck=%temp%\ChkState.dir
Set _OS=6
Ver|Findstr /I /C:"Version 5">Nul
If %Errorlevel%==0 Set _OS=5 & Set /A _Delay=_Delay*1000
:_StartMon
Call :_SetBaseline "%_Base%" "%_Monitor%"
:_MonLoop
If %_OS%==5 (Ping 1.0.0.0 -n 1 -w %_Delay%>Nul) Else Timeout %_Delay%>Nul
Call :_SetBaseline "%_Chck%" "%_Monitor%"
FC /A /L "%_Base%" "%_Chck%">Nul
If %ErrorLevel%==0 Goto _MonLoop
echo ___ Backing up JobBoss files...
::%backupcmd% "C:\Users\john.weakley\Desktop\Test Source Folder" "C:\Users\me\Desktop\Test Destination Folder\"
::CALL "C:\users\me\Desktop\Test Source Folder\Test.bat"
ECHO ___ Checking for new file revisions...
%backupcmd% "!lastName!!baseExt!" "C:\Users\me\Desktop\Test Source Folder\!baseName!! baseExt!"
Echo.Backup Complete!
Goto :_StartMon
:::::::::::::::::::::::::::::::::::::::::::::::::::
:: Subroutine
:::::::::::::::::::::::::::::::::::::::::::::::::::
:_SetBaseline
If Exist "%temp%\tempfmstate.dir" Del "%temp%\tempfmstate.dir"
For /F "Tokens=* Delims=" %%I In ('Dir /S "%~2"') Do (
Set _Last=%%I
>>"%temp%\tempfmstate.dir" Echo.%%I
)
>"%~1" Findstr /V /C:"%_Last%" "%temp%\tempfmstate.dir"
Goto :EOF
You need to enable delayed expansion in order to support !VAR! syntax.
Change your first line to:
#echo off & setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

Resources