Batch Script Substring from string - batch-file

Ok, I have been playing around with this for a while and am getting no where. I need to pull the KB number out from a line.
The issue i am having is that some of the KB numbers are 6 characters and some are 7, and can't seem to find a way that will work to error detect the two.
The Two types of errors this makes is as follows
The First one should only have been displayed 6 characts so it added the extra "-" at the end.
x64 KB890830- 2012\MS12-000\WinSec-KB890830-006-P58310-Windows-KB890830-x64-V4.9.exe
While the second error shows the random "_" because it uses the first KB shown not the second.
ia64 KB_942288 2012\MS12-000\WinSec-KB_942288-007-P58312-WindowsServer2003-KB942288-v4-ia64.exe
EDIT
Batch File So Far
#ECHO OFF
SETLOCAL enableDelayedExpansion
IF EXIST Export.csv DEL Export.csv
FOR /F "tokens=*" %%I in ('dir /s /b *.*') DO CALl:Generate "%%I"
pause
:Generate
SETLOCAL
IF "%~x1" NEQ ".exe" (
If "%~x3" NEQ ".msu" (
GOTO:EOF
)
)
CALL:FindArchitecture %1
CALL:FindKB %1
CALL:PathFix %1
ECHO %Architecture%,%KB%,%FilePath%>>Export.csv
CALL:Cleanup
ENDLOCAL
GOTO:EOF
:FindArchitecture
ECHO %1 | FINDSTR "x64"
IF "%ERRORLEVEL%"=="0" (
SET Architecture=x64
SET Count+=1
)
ECHO %1 | FINDSTR "x86"
IF "%ERRORLEVEL%"=="0" (
SET Architecture=x86
SET Count+=1
)
ECHO %1 | FINDSTR "ia64"
IF "%ERRORLEVEL%"=="0" (
SET Architecture=ia64
SET Count+=1
)
IF "%Count%" GTR "1" (
SET Architecture=Error
)
SET Count=0
GOTO:EOF
:FindKB
set KBNum="%~1"
set "KBNum=!KBNum:*-KB=!"
ECHO !KBNum!|findstr /I /E /R /c:"-KB[0-9][0-9][0-9][0-9][0-9][0-9][0-9]" >nul
SET "KB=KB!KBNum:~0,7!"
IF "%KB%" NEQ "" GOTO:EOF
ECHO !KBNum!|findstr /I /E /r /c:"-KB[0-9][0-9][0-9][0-9][0-9][0-9]" >nul
SET "KB=KB!KBNum:~0,6!"
GOTO:EOF
:PathFix
set Path_to_convert=%~1
set Reference_path=%~dp0
set FilePath=!Path_to_convert:*%Reference_path%=!
GOTO:EOF
:Cleanup
SET KBNum=
SET KB=
SET Count=
SET Architecture=
set InstallerPath=
set PathRemoval=
set Path=
GOTO:EOF

OK - siginificant edit after seeing comments from Ken White and the OP.
I'm not sure if you need this, but FINDSTR with a regular expression can validate that the line has the pattern: "-KB" followed by 7 digits, followed by "-".
echo somestring|findstr /r /c:"-KB[0-9][0-9][0-9][0-9][0-9][0-9][0-9]-" >nul
Then use substitution to remove everything from the beginning through "KB-".
Then use FINDSTR to verify that the first 7 remaining characters are digits. If not, then loop back and replace up to the next "-KB", etc.
Then you just need to take the first remaining 7 characters.
#echo off
:parseVal
setlocal enableDelayedExpansion
set val="%~1"
echo !val!|findstr /r /c:"-KB[0-9][0-9][0-9][0-9][0-9][0-9][0-9]-" >nul || (
echo Invalid format - KB value not found
exit /b
)
:parseVal2
set "val=!val:*-KB=!"
echo !val!|findstr /brc:"[0-9][0-9][0-9][0-9][0-9][0-9][0-9]-" >nul || goto :parseVal2
set "val=KB!val:~0,7!"
echo val=!val!
exit /b
EDIT
I'm not sure what you did to accept the 6 digit numbers, but the following regex expressions will work with numbers of any length.
For the 1st regex: findstr /rc:"-KB[0-9]*-"
For the 2nd regex: findstr /brc:"[0-9]*-"
Then you can use either of the following to extract out the number when you don't know the length:
for /f "delims=-" %%A in ("!val!") do set "val=KB%%A"
or
set val=KB%val:-=&REM %"

Related

How do I substring a dynamic variable value in windows batch scripting

Not able to substring the dynamic variable inside forloop in Windows batch script.
I have the properties file in my git hub in the below format.
"collectionName=TestCollectionRun.json=test"
So I have written the below code to fetch this values.But the requirement is that I need to strip of the '.json' part from collection name.With the below code I am not able to set/echo that value.Can you please help on this!
#ECHO ON
:BEGIN
IF EXIST "test.properties" ECHO Found properties file, reading file..
SET props=test.properties
setlocal EnableDelayedExpansion
For /F "delims== tokens=1,2,3" %%G in (%props%) Do (
if "%%I" EQU "test" if "%%G" EQU "collectionName" SET collName=%%H(
SET finalCollName=%collName%:~0,-5
ECHO %finalCollName%
)
)
:END
We need the ECHO to return "TestCollectionRun".currently its not returning anything.
For /F "delims== tokens=1,2,3" %%G in (%props%) Do (
if "%%I" EQU "test" if "%%G" EQU "collectionName" SET "collName=%%~nH"&echo %%~nH
)
ECHO %CollName%
Note the second ) is now redundant. Your problem has to do with delayedexpansion which you are invoking but not using. call %%collname%% within the for loop would have shown the value after assignment if required.
This code works by interpreting %%H as a filename and assigning simply the name part of %%H (%%~nH)
Given a line content of collectionName=TestCollectionRun.json=test, here's a quick rewrite of what I think you're tring to do:
#Echo Off
Set "props=test.properties"
If Not Exist "%props%" (
Echo Properties file not found!
Echo Exiting..
Timeout /T 3 /NoBreak >NUL
Exit /B
)
Echo Found properties file, reading file..
For /F "UseBackQ Tokens=1-3 Delims==" %%A In ("%props%") Do (
If /I "%%C" == "test" If /I "%%A" == "collectionName" Echo %%~nB
)
Pause
If you wanted to do something with the collection name within the loop then you would probably need to use delayed expansion:
#Echo Off
SetLocal DisableDelayedExpansion
Set "props=test.properties"
If Not Exist "%props%" (
Echo Properties file not found!
Echo Exiting..
Timeout /T 3 /NoBreak >NUL
Exit /B
)
Echo Found properties file, reading file..
For /F "UseBackQ Tokens=1-3 Delims==" %%A In ("%props%") Do (
If /I "%%C" == "test" If /I "%%A" == "collectionName" (
Set "collName=%%B"
SetLocalEnableDelayedExpansion
Echo !collName!
Rem Perform substring task on the variable named collName
Set "finalCollName=!collName%:~0,-5!"
Echo !finalCollName!
EndLocal
)
)
Pause
Note, these answers will not work, as is, if your string is surrounded by doublequotes, (as in your question body), or if the line content differs (e.g. begins with spaces or tabs).
[Edit /]
Looking at your 'after the fact' question in the comments, it is clear that you do not need to substring the variable at all, so should use the first method posted:
Echo Found properties file, reading file..
For /F "UseBackQ Tokens=1-3 Delims==" %%A In ("%props%") Do (
If /I "%%C" == "test" If /I "%%A" == "collectionName" (
newman run "%%B" -e "%envName%" --insecure --reporters cli,htmlextra --reporter-htmlextra-export "newman\%BUILD_NUMBER%\%%~nB.html" --disable-unicode
)
)
Pause
This assumes that both %envName% and %BUILD_NUMBER% have been previously defined correctly.

Batch script to check the content and file name

I have a code in batch script which will check if the name of the file is same or content of the file is same or not. Also it will updat the ini file to 0 or 1
0 - if the file names are different
1 - if the file names are different
Below is my code
#ECHO OFF
CLS
del /s C:\deep\output.log > NUL
for %%i in (C:\deep\*.DAT) do (
for /f "tokens=1,2 delims= " %%G in (app.ini) do set %%G=%%H
echo Rungmis %rungmis%
fc C:\deep\MAI_ZSYS_MOVE.DAT %%i > NUL
if errorlevel 1 (
CALL :error
echo C:\deep\MAI_ZSYS_MOVE.DAT and %%i are different >>output.log
set /a rungmis=0
echo Rungmis %rungmis%
timeout 5
) ELSE (
CALL :next
echo C:\deep\MAI_ZSYS_MOVE.DAT and %%i are same >>output.log
set /a rungmis=1
echo Rungmis %rungmis%
timeout 5
)
)
for %%I in (rungmis) do (
setlocal enabledelayedexpansion
type app.ini | find /v "%%I=">settings.tmp
move /y settings.tmp gmisapp.ini
echo %%I=!%%I!>>app.ini
)
type app.ini
timeout 5
It is updating the .ini flag (rungmis flag) to 0 or 1. But the problem which i am facing is whenever the ini is getting updated the flag (rungmis) is getting updated at the last line of the ini
Actual app.ini file
[TO_RUN_GMIS]
rungmis=1
;0 means GMIS will run
;1 means GMIS will not run
[Registry_Directories]
ArchivePath=D:\maibackup\
ImportPath=D:\gmisdata\
ExportPath=D:\www\GMIS\excel\
DataSource=GMIS_DEV_NEW
app.ini after getting updated
[TO_RUN_GMIS]
;0 means GMIS will run
;1 means GMIS will not run
[Registry_Directories]
ArchivePath=D:\maibackup\
ImportPath=D:\gmisdata\
ExportPath=D:\www\GMIS\excel\
rungmis=1
can anyone please help me out with that?
Please give this a try.
#ECHO OFF
CLS
del /s C:\deep\output.log > NUL
for %%i in (C:\deep\*.DAT) do (
for /f "tokens=1,2 delims= " %%G in (app.ini) do set %%G=%%H
echo Rungmis %rungmis%
fc C:\deep\MAI_ZSYS_MOVE.DAT %%i > NUL
if errorlevel 1 (
CALL :error
echo C:\deep\MAI_ZSYS_MOVE.DAT and %%i are different >>output.log
set /a rungmis=0
echo Rungmis %rungmis%
timeout 5
) ELSE (
CALL :next
echo C:\deep\MAI_ZSYS_MOVE.DAT and %%i are same >>output.log
set /a rungmis=1
echo Rungmis %rungmis%
timeout 5
)
)
for /f "tokens=*" %%a in ('type "app.ini" ^| find /v /n "" ^& break ^> "app.ini"') do (
set "str=%%a"
setlocal enabledelayedexpansion
set "str=!str:*]=!"
if "!str:~0,7!"=="rungmis" set "str=!str:~0,-1!%rungmis%"
>>app.ini echo(!str!
endlocal
)
type app.ini
timeout 5
So we simply do a type on the file and add some additional characters to ensure we replicate newlines as well. We then get rid of those characters before printing to file. But first we search for the string rungmis and replaces its value with the value you determined earlier in the script. Then each line gets printed back into the app.ini file with the replacement value.

How can we split string using windows bat

How can we split string using windows bat script?
for below .bat code snippet
#echo off & setlocal EnableDelayedExpansion
set j=0
for /f "delims=""" %%i in (config.ini) do (
set /a j+=1
set con!j!=%%i
call set a=%%con!j!%%
echo !a!
(echo !a!|findstr "^#">nul 2>nul && (
rem mkdir !a!
) || (
echo +)
rem for /f "tokens=2" %%k in(config.ini) do echo %%k
)
)
pause
below config file
Q
What's wrong when I del rem at the begin of rem for /f "tokens=2" %%k in(config.ini) do echo %%k
How can I get the /path/to/case and value as a pair?
for /f xxxx in (testconfig.ini) do (set a=/path/to/case1 set b=vaule1)
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q43407067.txt"
set j=0
for /f "delims=""" %%i in (%filename1%) do (
set /a j+=1
set con!j!=%%i
call set a=%%con!j!%%
echo !a! SHOULD BE EQUAL TO %%i
(echo !a!|findstr "^#">nul 2>nul && (
echo mkdir !a!
) || (
echo +)
for /f "tokens=2" %%k IN ("%%i") do echo "%%k"
for /f "tokens=1,2" %%j IN ("%%i") do echo "%%j" and "%%k"
)
)
ECHO ----------------------------
SET con
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
I used a file named q43407067.txt containing your data for my testing.
(These are setting that suit my system)
SO - to address your problems:
because the ) on that line closes the ( on the previous. The ) on that line closes the ( on the one prior. (I changed the rem to an echo so that the code would produce something visible) The first ( on the (echo !a! line is closed by the ) on the line following the (now) two for /f commands. and the ( on the for..%%i..do( is closed by the final ) before the echo -----
You can't delete that ) because it's participating in a parenthesis-pair.
You need a space between the in and the (.
I've shown a way. See for /?|more from the prompt for documentation (or many articles here on SO)
In your code, !a! is the same as %%i - so I've no idea why you are conducting all the gymnastics - doubtless to present a minimal example showing the problem.
Note that since the default delimiters include Space then if any line contains a space in the /path/to/case or value then you'll have to re-engineer the approach.
I' not sure if I understand what exactly it is you need, so what follows may not suit your needs:
#Echo Off
SetLocal EnableDelayedExpansion
Set "n=0"
For /F "Delims=" %%A In (testConfig.ini) Do (Set "_=%%A"
If "!_:~,1!"=="#" (Set/A "n+=1", "i=0"
Echo=MD %%A
Set "con[!n!]!i!=%%A") Else (For /F "Tokens=1-2" %%B In ('Echo=%%A'
) Do (Set/A "i+=1"
Set "con[!n!]!i!=%%B"&&Set/A "i+=1"&&Set "con[!n!]!i!=%%C")))
Set con[
Timeout -1
GoTo :EOF
remove Echo= on line 6 if you are happy with the output and really want to create those directories

Windows Batch FOR Loop improvement

I have a batch to check the duplicate line in TXT file (over one million line) with 13MB, that will be running over 2hr...how can I speed up that? Thank you!!
TXT file
11
22
33
44
.
.
.
44 (over one million line)
Existing Batch
setlocal
set var1=*
sort original.txt>sort.txt
for /f %%a in ('type sort.txt') do (call :run %%a)
goto :end
:run
if %1==%var1% echo %1>>duplicate.txt
set var1=%1
goto :eof
:end
This should be the fastest method using a Batch file:
#echo off
setlocal EnableDelayedExpansion
set var1=*
sort original.txt>sort.txt
(for /f %%a in (sort.txt) do (
if "%%a" == "!var1!" (
echo %%a
) else (
set "var1=%%a"
)
)) >duplicate.txt
This method use findstr command as in aschipfl's answer, but in this case each line and its duplicates are removed from the file after being revised by findstr. This method could be faster if the number of duplicates in the file is high; otherwise it will be slower because the high volume data manipulated in each turn. Just a test may confirm this point...
#echo off
setlocal EnableDelayedExpansion
del duplicate.txt 2>NUL
copy /Y original.txt input.txt > NUL
:nextTurn
for %%a in (input.txt) do if %%~Za equ 0 goto end
< input.txt (
set /P "line="
findstr /X /C:"!line!"
find /V "!line!" > output.txt
) >> duplicate.txt
move /Y output.txt input.txt > NUL
goto nextTurn
:end
#echo off
setlocal enabledelayedexpansion
set var1=*
(
for /f %%a in ('sort q42574625.txt') do (
if "%%a"=="!var1!" echo %%a
set "var1=%%a"
)
)>"u:\q42574625_2.txt"
GOTO :EOF
This may be faster - I don't have your file to test against
I used a file named q42574625.txt containing some dummy data for my testing.
It's not clear whether you want only one instance of a duplicate line or not. Your code would produce 5 "duplicate" lines if there were 6 identical lines in the source file.
Here's a version which will report each duplicated line only once:
#echo off
setlocal enabledelayedexpansion
set var1=*
set var2=*
(
for /f %%a in ('sort q42574625.txt') do (
if "%%a"=="!var1!" IF "!var2!" neq "%%a" echo %%a&SET "var2=%%a"
set "var1=%%a"
)
)>"u:\q42574625.txt"
GOTO :EOF
Supposing you provide the text file as the first command line argument, you could try the following:
#echo off
for /F "usebackq delims=" %%L in ("%~1") do (
for /F "delims=" %%K in ('
findstr /X /C:"%%L" "%~1" ^| find /C /V ""
') do (
if %%K GTR 1 echo %%L
)
)
This returns all duplicate lines, but multiple times each, namely as often as each occurs in the file.

Xor a string in a bat file?

In short I want to give my friend a bat file which does the below (untested)
echo Your mother is so fat
pause
echo the recursive function computing her mass causes a stack overflow
I might copy/paste him the bat file so I don't want the punch line to be ruined. How can I hide the text? I was thinking I can store the string in a variable and before I echo it I should XOR each letter with 32. But I have no idea how to take a string, XOR each letter than echo it to display the joke. How might I hide the text? I could also BASE64 encode/decode it but IDK how to do that either if I am only using a bat file
1) Here's one way to hide the text using mshta as a command line tool (with ascii codes in this case) :
#echo off
mshta vbscript:execute("CreateObject(""Scripting.FileSystemObject"").GetStandardStream(1).Write(Chr(89) & Chr(111)& Chr(117) & Chr(114) & Chr(32) & Chr(109) & Chr(97) & Chr(109) & Chr(97) & Chr(32) ):Close")|more
2) You can use CERTUTIL to encode/decode base64/hex files but it requires a temporary file that can be silently deleted (more info ):
echo 796f7572206d616d6120697320736f20666174>"%temp%\fat.hex"
certutil -decodehex "%temp%\fat.hex" "%temp%\fat.txt" >nul 2>&1
type "%temp%\fat.txt"
del /q /f "%temp%\fat.txt"
3) Dbenham's hex print function
#echo off
setlocal
::Define a Linefeed variable
set LF=^
::above 2 blank lines are critical - do not remove.
::Create a string variable with encoded TABs
call :hexprint "0x790x6f0x750x720x200x6d0x610x6d0x610x200x690x730x200x730x6f0x200x660x610x74" var
echo %var%
exit /b
:hexPrint string [rtnVar]
for /f eol^=^%LF%%LF%^ delims^= %%A in (
'forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(%~1"'
) do if "%~2" neq "" (set %~2=%%A) else echo(%%A
exit /b
4) carlos' genCar function that uses MAKECAB:
#echo off
setlocal
break>fat.txt
for %%# in (121 111 117 114 32 109 97 109 97 32 105 115 32 115 111 32 102 97 116) do (
call :genChar %%#
type %%#.chr>>fat.txt
del /q /f %%#.chr >nul 2>&1
)
type fat.txt
del /q /f fat.txt
goto :eof
:genChar
setlocal
set "USAGE=echo:Usage: Supply an integer 0-255& goto :EOF"
if "%~1" equ "" %USAGE%
set /a "val=%~1" 2>nul
if "%~1" neq "%val%" %USAGE%
if %~1 lss 0 %USAGE%
if %~1 gtr 255 %USAGE%
set tempfile=%~1.tmp
set "options=/d compress=off /d reserveperdatablocksize=26"
if %~1 neq 26 (type nul >"%tempfile%"
makecab %options% /d reserveperfoldersize=%~1 "%tempfile%" %~1.chr >nul
type %~1.chr | (
(for /l %%N in (1 1 38) do pause)>nul&findstr "^">"%tempfile%")
>nul copy /y "%tempfile%" /a %~1.chr /b
del "%tempfile%"
) else (copy /y nul + nul /a 26.chr /a >nul)
endlocal
for more cryptic script you can combine hem.Only MSHTA and MAKECAB solutions will work on every windows machine. FORFILES and CERTUTIL are default form Vista and above I think.It is possible to create a few more examples ...
This is a subject near and dear to my heart because I did something similar in my implementation of the classic Colossal Cave Adventure game as a Windows batch file.
Within the game script I selectively encrypt display text, variable names, and comments. The code to decode the encrypted text is embedded directly within the same script! I write the source code for the game normally, and use braces to denote what portion is to be encrypted. A function within the game is able to generated the encrypted form of itself!
I used a simple symmetric rotation cipher, so really it is more obfuscation than encryption. But that is all that is needed for both the game, and your situation.
I've extracted a simplified version of the routines and provide them below.
The first script is a standalone script that selectively encrypts text within a source file and writes the result to stdout. Simply redirect the output to a new file to get the encrypted version of the file.
selectiveROT13.bat
#echo off
:selectiveROT13 InFile
::
:: Selectively applies the simple "rotate alphabet 13 places" cipher
:: to the contents of file InFile. Only text between curly braces
:: is affected. The affected content can span multiple lines.
::
:: Writes the results to stdout.
:: Percent completion is continuously written to stderr.
::
setlocal enableDelayedExpansion
set "upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set "lower=abcdefghijklmnopqrstuvwxyz"
for /l %%A in (0 1 25) do (
set /a "B=(%%A+13)%%26"
for /f %%B in ("!B!") do (
set "upper!upper:~%%A,1!=!upper:~%%B,1!"
set "lower!lower:~%%A,1!=!lower:~%%B,1!"
)
)
setlocal disableDelayedExpansion
>&2 cls
set "active="
for /f %%N in ('type %1^|find /c /v ""') do set /a "lnCnt=%%N, pct=-1"
for /f "skip=2 tokens=1,* delims=[]" %%a in ('find /v /n "" %1') do (
set "ln=%%b"
setlocal enableDelayedExpansion
set "str=A!ln!"
set "len=0"
for /L %%A in (12,-1,0) do (
set /a "len|=1<<%%A"
for %%B in (!len!) do if "!str:~%%B,1!"=="" set /a "len&=~1<<%%A"
)
set /a len-=1
set rtn=
for /l %%n in (0,1,!len!) do (
set "c=!ln:~%%n,1!"
if "!c!" equ "{" set "active=1"
if "!c!" equ "}" set "active="
if defined active if defined upper!c! for /f %%c in ("!c!") do (
if "!upper:%%c=%%c!" equ "!upper!" (
set "c=!upper%%c!"
) else (
set "c=!lower%%c!"
)
)
set "rtn=!rtn!!c!"
)
echo(!rtn!
for %%A in ("!active!") do (
endlocal
set "active=%%~A"
)
)
exit /b 0
Below is your joke program with a simplified version of the code to decode encrypted text. My original code worked with string variables, but this version works with string literals. The source script is written normally, without encryption. Braces indicate which code is to be encrypted. Besides your joke, I've included documentation and examples to demonstrate some of the features.
joke_src.bat
#echo off
setlocal enableDelayedExpansion
call :init
:: Disable delayed expansion to protect ! within string literals
setlocal disableDelayedExpansion
:: Curly braces are used to denote text that should be encrypted.
:: Encryption can span multiple lines
:: {
:::Line1
:::Line2
:::Line3
:: }
:: I defined a simple SHOW macro that expands to CALL :SHOW
:: Use the %show% macro to display encrypted text.
:: The braces can be hidden by using the undefined %{% & %}% variables
%show% %{%"Quote literals ("") must be doubled ("""") in the source"%}%
:: Here I use a FOR loop to show all encrypted lines within this script
:: that begin with :::
echo(
for /f "delims=: tokens=*" %%A in ('findstr /b ":::" "%~f0"') do %show% "%%A"
echo(
echo And now it is time for a little joke.
echo(
echo Your mother is so fat...
pause
%show% %{%"the recursive function computing her mass causes a stack overflow!"%}%
exit /b
:show Str
::{
:: Applies the simple "rotate alphabet 13 places" cipher to string Str
:: and writes the result to stdout. Consecutive quotes ("") are converted
:: into a single quote (").
::}
setlocal disableDelayedExpansion
set "str=%~1"
setlocal enableDelayedExpansion
set "str=!str:""="!^"
if defined {obfuscated} (
set "len=0"
set "str2=.!str!"
for /L %%A in (12,-1,0) do (
set /a "len|=1<<%%A"
for %%B in (!len!) do if "!str2:~%%B,1!"=="" set /a "len&=~1<<%%A"
)
set /a len-=1
set rtn=
for /l %%n in (0,1,!len!) do (
set "c=!str:~%%n,1!"
if defined {upper}!c! for /f %%c in ("!c!") do (
if "!{upper}:%%c=%%c!" equ "!{upper}!" (
set "c=!{upper}%%c!"
) else (
set "c=!{lower}%%c!"
)
)
set "rtn=!rtn!!c!"
)
) else set "rtn=!str!"
echo(!rtn!
exit /b 0
:init
set "}="
set "{="}
set "{upper}=ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set "{lower}=abcdefghijklmnopqrstuvwxyz"
for /l %%A in (0 1 25) do (
set /a "B=(%%A+13)%%26"
for /f %%B in ("!B!") do (
set "{upper}!{upper}:~%%A,1!=!{upper}:~%%B,1!"
set "{lower}!{lower}:~%%A,1!=!{lower}:~%%B,1!"
)
)
set "{obfuscated}="
set "{obfuscationTest}={A}"
if "!{obfuscationTest}:A=!" equ "!{obfuscationTest}!" set {obfuscated}=1
set "show=call :show"
exit /b
The following command will generate the encrypted version of the script:
selectiveROT13 joke_src.bat >joke.bat
Below is the encrypted form. This is what you would send to your friend. (Without the extra documentation and examples of course)
joke.bat
#echo off
setlocal enableDelayedExpansion
call :init
:: Disable delayed expansion to protect ! within string literals
setlocal disableDelayedExpansion
:: Curly braces are used to denote text that should be encrypted.
:: Encryption can span multiple lines
:: {
:::Yvar1
:::Yvar2
:::Yvar3
:: }
:: I defined a simple SHOW macro that expands to CALL :SHOW
:: Use the %show% macro to display encrypted text.
:: The braces can be hidden by using the undefined %{% & %}% variables
%show% %{%"Dhbgr yvgrenyf ("") zhfg or qbhoyrq ("""") va gur fbhepr"%}%
:: Here I use a FOR loop to show all encrypted lines within this script
:: that begin with :::
echo(
for /f "delims=: tokens=*" %%A in ('findstr /b ":::" "%~f0"') do %show% "%%A"
echo(
echo And now it is time for a little joke.
echo(
echo Your mother is so fat...
pause
%show% %{%"gur erphefvir shapgvba pbzchgvat ure znff pnhfrf n fgnpx biresybj!"%}%
exit /b
:show Str
::{
:: Nccyvrf gur fvzcyr "ebgngr nycunorg 13 cynprf" pvcure gb fgevat Fge
:: naq jevgrf gur erfhyg gb fgqbhg. Pbafrphgvir dhbgrf ("") ner pbairegrq
:: vagb n fvatyr dhbgr (").
::}
setlocal disableDelayedExpansion
set "str=%~1"
setlocal enableDelayedExpansion
set "str=!str:""="!^"
if defined {boshfpngrq} (
set "len=0"
set "str2=.!str!"
for /L %%A in (12,-1,0) do (
set /a "len|=1<<%%A"
for %%B in (!len!) do if "!str2:~%%B,1!"=="" set /a "len&=~1<<%%A"
)
set /a len-=1
set rtn=
for /l %%n in (0,1,!len!) do (
set "c=!str:~%%n,1!"
if defined {hccre}!c! for /f %%c in ("!c!") do (
if "!{hccre}:%%c=%%c!" equ "!{hccre}!" (
set "c=!{hccre}%%c!"
) else (
set "c=!{ybjre}%%c!"
)
)
set "rtn=!rtn!!c!"
)
) else set "rtn=!str!"
echo(!rtn!
exit /b 0
:init
set "}="
set "{="}
set "{hccre}=ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set "{ybjre}=abcdefghijklmnopqrstuvwxyz"
for /l %%A in (0 1 25) do (
set /a "B=(%%A+13)%%26"
for /f %%B in ("!B!") do (
set "{hccre}!{hccre}:~%%A,1!=!{hccre}:~%%B,1!"
set "{ybjre}!{ybjre}:~%%A,1!=!{ybjre}:~%%B,1!"
)
)
set "{boshfpngrq}="
set "{boshfpngvbaGrfg}={N}"
if "!{boshfpngvbaGrfg}:A=!" equ "!{boshfpngvbaGrfg}!" set {boshfpngrq}=1
set "show=call :show"
exit /b
The beauty of this system is that both joke.bat and joke_src.bat generate the exact same output:
Quote literals (") must be doubled ("") in the source
Line1
Line2
Line3
And now it is time for a little joke.
Your mother is so fat...
Press any key to continue . . .
the recursive function computing her mass causes a stack overflow!
Another nice feature is that selectiveROT13.bat can be applied to joke.bat to regenerate the original un-encrypted source.
This code creates a base64 encoded file:
#echo off
set "var=the recursive function computing her mass causes a stack overflow"
>file.tmp echo %var%
certutil -f -encode file.tmp file.tmp2 >nul
echo file.tmp2|find /v "-----" >file.txt
del file.tmp?
pause
and you can use the file like so (adding echo at the start of each line of the encoded file):
#echo off
cls
echo Your mother is so fat
pause
(
echo dGhlIHJlY3Vyc2l2ZSBmdW5jdGlvbiBjb21wdXRpbmcgaGVyIG1hc3MgY2F1c2Vz
echo IGEgc3RhY2sgb3ZlcmZsb3cNCg==
)>file.tmp
certutil -f -decode file.tmp file.txt >nul
timeout /t 2 /nobreak >nul
type file.txt
timeout /t 5 /nobreak >nul
I think you can just replace some chars with others in pure BAT without any temporary files using following string replacing script.
%str:old_char=new_char%
For example, I have defined some encoding and decoding functions. The codes are attached here, and it will print what you want.
#echo off
set str1=Y urke ohtrkmsks kfao
set str2=ohtkrtcursmvtkfuncom nkc epuomngkhtrkeasskcaustskaksoacik vtrfl w
call :decode "%str1%"
call :decode "%str2%"
pause
goto :eof
:decode
set "str=%~1"
set str=%str: =#%
set str=%str:k= %
set str=%str:i=k%
set str=%str:m=i%
set str=%str:e=m%
set str=%str:t=e%
set str=%str:o=t%
set str=%str:#=o%
echo %str%
goto :eof
I also attached the encoding script below.
#echo off
set str1=Your mother is so fat
set str2=the recursive function computing her mass causes a stack overflow
call :encode "%str1%"
call :encode "%str2%"
pause
goto :eof
:encode
set "str=%~1"
set str=%str:o=#%
set str=%str:t=o%
set str=%str:e=t%
set str=%str:m=e%
set str=%str:i=m%
set str=%str:k=i%
set str=%str: =k%
set str=%str:#= %
echo %str%
goto :eof

Resources