I have a bat script that asks for user input with the next line
SET /P returnString=Enter string: %=%
Now I want default input visible on the command line, like:
Enter string: defaultstring
To clarify: I don't want a default value if no input is given, I want the default value visible and editable on the command line, so in the case described above the defaultstring could be replaced for a different text.
Is this possible with SET in a batch file? If not, how could I accomplish this?
Here is a Batch + JScript hybrid script that prompts with a default value.
#if (#CodeSection == #Batch) #then
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: The first line in the script is...
:: in Batch, a valid IF command that does nothing.
:: in JScript, a conditional compilation IF statement that is false.
:: So the following section is omitted until the next "[at]end".
:: Note: the "[at]then" is required for Batch to prevent a syntax error.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Batch Section
#echo off
setlocal
set "Input="
set "Default=Hello World"
title MyUniqueTitle
CScript //E:JScript //Nologo "%~f0" "MyUniqueTitle" "%Default%"
set /p "Input=> Prompt: "
if defined Input set "Input=%Input:"=%"
echo(%Input%
endlocal
exit /b 0
:: End of Batch
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#end
////////////////////////////////////////////////////////////////////////////////
// JScript Section
try
{
var WshShell = WScript.CreateObject('WScript.Shell');
var Title = WScript.Arguments.Item(0);
var Message = WScript.Arguments.Item(1);
WshShell.AppActivate(Title);
WshShell.SendKeys(Message);
WScript.Quit(0);
}
catch(e)
{
WScript.Echo(e);
WScript.Quit(1);
}
WScript.Quit(2);
Well, it's not exactly what you asked for but I think it's better. This will create a browseforfolder dialog and let your user pick what folder to use. In this example r is the return variable from the function. It will return an errorlevel of 0 if a folder is chosen and 1 if the cancel button is hit.
#Echo off
setlocal
Call :BrowseFolder "Enter path to folder" "C:\scripts\" r
echo %r%
echo %errorlevel%
pause
Goto :EOF
:BrowseFolder <Title> <DefaultStartPath> <Return>
setlocal
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs% echo set sh=wscript.CreateObject("Shell.Application")
>>%vbs% echo set f=sh.BrowseForFolder(0,%1,0,%2)
>>%vbs% echo if typename(f)="Nothing" Then
>>%vbs% echo wscript.echo "Dialog Cancelled"
>>%vbs% echo wscript.Quit(1)
>>%vbs% echo end if
>>%vbs% echo set fs=f.Items():set fi=fs.Item()
>>%vbs% echo p=fi.Path:wscript.echo p
for /f "tokens=*" %%a in ('cscript //nologo %vbs%') do set result=%%a
if exist %vbs% del /f /q %vbs%
if "%result%" EQU "Dialog Cancelled" (set a=1) else set a=0
endlocal & set %3=%result% & exit /b %a%
Related
I have no idea how to get what described here using an Win CMD batch script:
pseudo-code
set aPath=C:\just\a\long\path\to\a\file\in\the\file\system
set aDir=file
... some logic here
echo %result%
Should print
C:\just\a\long\path\to\a\file
It should stop at the first occurrence found, but it would be nice to specify also the occurence (optional).
ONLY Windows CMD SOLUTIONS ARE WELCOME no Powershell code nor external tools, please. I'm looking for a pure Windows CMD solution.
I'm not quite sure to what you refer with occurence
Using a shuffle approach and self modifying code to get the dir levels
:: Q:\Test\2019\08\29\SO_57717256.cmd
#Echo off & Setlocal EnableDelayedExpansion
set "aPath=C:\just\a\long\path\to\a\file\in\the\file\system"
set "aDir=file"
echo aPath = %aPath%
echo aDir = %aDir%
::... some logic here
set "intermediate=!apath:*%aDir%=!"
set "result=!aPath:%intermediate%=!"
:: and some vodoo there ;-)
Set i=0
Set "aPath=%aPath:\="&Set /a i+=1&Set "aPath[!i!]=%"
echo result= %result%
for /l %%L in (1,1,%i%) Do if "%aDir%"=="!aPath[%%L]!" (
echo aPath[%%L] = !aPath[%%L]! ^<^<^< matches aDir %aDir%
) else (
echo aPath[%%L] = !aPath[%%L]!
)
Sample output:
> Q:\Test\2019\08\29\SO_57717256.cmd
aPath = C:\just\a\long\path\to\a\file\in\the\file\system
aDir = file
result= C:\just\a\long\path\to\a\file
aPath[1] = just
aPath[2] = a
aPath[3] = long
aPath[4] = path
aPath[5] = to
aPath[6] = a
aPath[7] = file <<< matches aDir file
aPath[8] = in
aPath[9] = the
aPath[10] = file <<< matches aDir file
aPath[11] = system
Here is a little approach using a recursive sub-routine, just for fun:
#echo off
set "aPath=C:\just\a\long\path\to\a\file\in\the\file\system"
set "aDir=file"
set "result=" & set "found="
call :RECURSIVE "%aPath%\."
if defined found echo/%result%
exit /B
:RECURSIVE
if "%~nx1" == "" set "result=%~dp1" & exit /B
call :RECURSIVE "%~dp1."
if defined found (exit /B) else set "result=%result%%~nx1\"
if /I "%~nx1" == "%aDir%" set "found=#" & set "result=%result:~,-1%"
This makes use of the ~ modifiers of command line or sub-routine arguments (parameters), which allow to split a path into pieces.
A simpler approach:
#echo off
setlocal EnableDelayedExpansion
set aPath=C:\just\a\long\path\to\a\file\in\the\file\system\filenot\file\folder
set aDir=file
echo %aPath%
rem This FOR is just for testing; remove it...
for /L %%n in (1,1,3) do (
set "n=%%n"
set "result="
for %%a in ("!aPath:\%aDir%\=" "!") do if !n! gtr 0 set "result=!result!%%~a\%aDir%\" & set /A n-=1
echo %%n: !result:~0,-1!
)
Output example:
C:\just\a\long\path\to\a\file\in\the\file\system\filenot\file\folder
1: C:\just\a\long\path\to\a\file
2: C:\just\a\long\path\to\a\file\in\the\file
3: C:\just\a\long\path\to\a\file\in\the\file\system\filenot\file
EDIT: An even simpler method with the aid of some magic:
#echo off
setlocal EnableDelayedExpansion
set aPath=C:\just\a\long\path\to\a\file\in\the\file\system\filenot\file\folder
set aDir=file
echo %aPath%
set n=%1
set "result="
set "p=%aPath:\=" & (if !n! gtr 0 set "result=!result!\!p!") & (if "!p!" equ "!aDir!" set /A n-=1) & set "p=%"
echo %1: %result:~1%
Output example:
C:\Tests> test 1
C:\just\a\long\path\to\a\file\in\the\file\system\filenot\file\folder
1: C:\just\a\long\path\to\a\file
C:\Tests> test 2
C:\just\a\long\path\to\a\file\in\the\file\system\filenot\file\folder
2: C:\just\a\long\path\to\a\file\in\the\file
I have found numerous ways to base64 encode whole files using the command-line on Windows, but I can't seem to find a simple way to batch encode just a "string" using a command-line utility.
How does one do this, for use in a batch file for example?
Here's a PowerShell one-liner you can run from a cmd console that'll Base64 encode a string.
powershell "[convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(\"Hello world!\"))"
It's probably not as fast as npocmaka's solution, but you could set a console macro with it.
doskey btoa=powershell "[convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(\"$*\"))"
doskey atob=powershell "[Text.Encoding]::UTF8.GetString([convert]::FromBase64String(\"$*\"))"
btoa Hello world!
btoa This is fun.
btoa wheeeeee!
atob SGVsbG8gd29ybGQh
Be advised that doskey doesn't work in batch scripts -- only the console. If you want do use this in a batch script, make a function.
#echo off
setlocal
call :btoa b64[0] "Hello world!"
call :btoa b64[1] "This is fun."
call :btoa b64[2] "wheeeeee!"
call :atob b64[3] SGVsbG8gd29ybGQh
set b64
goto :EOF
:btoa <var_to_set> <str>
for /f "delims=" %%I in (
'powershell "[convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(\"%~2\"))"'
) do set "%~1=%%I"
goto :EOF
:atob <var_to_set> <str>
for /f "delims=" %%I in (
'powershell "[Text.Encoding]::UTF8.GetString([convert]::FromBase64String(\"%~2\"))"'
) do set "%~1=%%I"
goto :EOF
Or if you'd prefer a batch + JScript hybrid:
#if (#CodeSection==#Batch) #then
#echo off & setlocal
call :btoa b64[0] "Hello world!"
call :btoa b64[1] "This is fun."
call :btoa b64[2] "wheeeeee!"
call :atob b64[3] SGVsbG8gd29ybGQh
set b64
goto :EOF
:btoa <var_to_set> <str>
:atob <var_to_set> <str>
for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0" %0 "%~2"') do set "%~1=%%I"
goto :EOF
#end // end batch / begin JScript hybrid code
var htmlfile = WSH.CreateObject('htmlfile');
htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=10" />');
WSH.Echo(htmlfile.parentWindow[WSH.Arguments(0).substr(1)](WSH.Arguments(1)));
Edit: batch + VBScript hybrid for #Hackoo:
<!-- : batch portion
#echo off & setlocal
call :btoa b64[0] "Hello world!"
call :btoa b64[1] "This is fun."
call :btoa b64[2] "wheeeeee!"
call :atob b64[3] SGVsbG8gd29ybGQh
set b64
goto :EOF
:btoa <var_to_set> <str>
:atob <var_to_set> <str>
for /f "delims=" %%I in ('cscript /nologo "%~f0?.wsf" %0 "%~2"') do set "%~1=%%I"
goto :EOF
: VBScript -->
<job>
<script language="VBScript">
Set htmlfile = WSH.CreateObject("htmlfile")
htmlfile.write("<meta http-equiv='x-ua-compatible' content='IE=10' />")
if WSH.Arguments(0) = ":btoa" then
WScript.Echo htmlfile.parentWindow.btoa(WSH.Arguments(1))
else
WScript.Echo htmlfile.parentWindow.atob(WSH.Arguments(1))
end if
</script>
</job>
According to the comments on the question, you can use certutil. e.g.,
certutil -encode raw.txt encoded.txt
or
certutil -f -encode raw.txt encoded.txt
The -f means "force overwrite". Otherwise you will get an error if the output file (encoded.txt above) already exists.
However, this will format the output into the encoded.txt file as if it were a certificate PEM file, complete with BEGIN and END lines, and split lines at the character max. So you would need to do further processing in a batch scenario, and a bit of extra work if the strings are long at all.
If you have OpenSSL for Windows installed you can use this to encode the string "Hello":
echo | set /p="Hello" | openssl base64
The | set /p= is to suppress the newline that echo usually outputs.
This will produce the same result as the following in bash:
echo -n 'Hello' | openssl base64
Output:
SGVsbG8=
This script can decode/encode base64 strings on every machine from XP and above without requiring installed .net or internet explorer 10/11.It even can handle special javascript escaped symbols:
// result is IkhlbGxvIg==
base64.bat -encode "\u0022Hello\u0022" -eval yes
// result is SGVsbG8=
base64.bat -encode "Hello"
This one accepts a single argument - the string you want to encode to base 64 and prints the result (but requires at least internet explorer 10 installed):
#echo off
setlocal
set "string=%~1"
::echo %string%^|mshta.exe "%~f0"
for /f "delims=" %%# in ('echo %string%^|mshta.exe "%~f0"') do (
set b64=%%#
)
set b64
endlocal&exit /b %errorlevel%
<HTA:Application
ShowInTaskbar = no
WindowsState=Minimize
SysMenu=No
ShowInTaskbar=No
Caption=No
Border=Thin
>
<meta http-equiv="x-ua-compatible" content="ie=10" />
<script language="javascript" type="text/javascript">
window.visible=false;
window.resizeTo(1,1);
var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
var fso2= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(0);
var string=fso2.ReadLine();
var encodedString = btoa(string);
fso.Write(encodedString);
window.close();
</script>
This can (technically) be done entirely within Batch, By Creating an encryption\decryption VBS script from within batch that can be called with the name of the Variable whose Data you wish to encrypt\decrypt.
Note: The below scipt is an Independant Subprogram.
Hybrid Batch Vbs Encrypter / Decrypter for passwords or other variables.
Performs the action on data stored in the defined file - does not create the file.
Note: file extension in vbs to match the filetype you save password/text to.
To use this program Call it with the name of the Variable you wish to set and the offset to perform.
However your Main program takes user input:
Set /p YourVariableName=
Store the Input to a File
ECHO %YourVariableName%>YourSaveFile.txt
Call it with a positive offset (IE: +26) to encrypt, and an equivalent Negative offset to Decrypt. (IE: -26)
CALL "Insert Filepath To Encrypter.bat Here" YourVariableName +26
Encrypter.bat
#ECHO OFF
REM :: Do NOT modify the variable names Below, DO INSERT the filepath you used to Store the Data Being Encrypted / Decrypted.
Set "VarName=%~1"
Set "offset=%~2"
Set "SaveLoc=Your Filepath Here"
<"%saveLoc%" (
Set /p encryptData=
)
(
ECHO Dim objFSO 'File System Object
ECHO Set objFSO = CreateObject("Scripting.FileSystemObject"^)
ECHO Dim objTS 'Text Stream Object
ECHO Const ForWriting = 2
ECHO Set objTS = objFSO.OpenTextFile("%SaveLoc%", ForWriting, True^)
ECHO objTS.Write(encode("%encryptData%"^)^)
ECHO wscript.sleep "1000"
ECHO function encode(s^)
ECHO For i = 1 To Len(s^)
ECHO newtxt = Mid( s, i, 1^)
ECHO newtxt = Chr(Asc(newtxt^) %offset%^)
ECHO coded = coded + (newtxt^)
ECHO Next
ECHO encode = coded
ECHO End function
ECHO objTS.Close(^)
ECHO Set bjFSO = Nothing 'Destroy the object.
ECHO Set objTS = Nothing 'Destroy the object.
) >%TEMP%\encrypter.vbs
START /wait %TEMP%\encrypter.vbs
DEL /Q "%TEMP%\encrypter.vbs"
GOTO :EOF
```
Be advised that doskey doesn't work in batch scripts -- only the console. If you want do use this in a batch script, make a function
or use a macro:
#echo off
====SETLOCAL DisableDelayedExpansion EnableExtensions
REM Initalize
set ^"LF=^
%===EXPANDS TO NOTHING===%
"
::\n is an escaped LF + caret for line continuation
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
REM MACRO
set ^"$b64.encode=FOR %%$ in (%%$ MainMacro) do if "%%$" == "MainMacro" (%\n%
^>nul %__APPDIR__%certutil.exe -f -encodehex args.tmp proc.tmp 0x40000001%\n%
type proc.tmp%\n%
echo(%\n%
del args.tmp proc.tmp%\n%
) 2^>nul ELSE ^<nul ^>args.tmp set/p="
REM EXAMPLES
%$b64.encode%"=I WILL FAIL (string cannot start with =)"
%$b64.encode%^" leading spaces/tabs will be stripped%\n%
but other characters are%\n%
OK!%\n%
;%%~dp$^&^|"""""""
Limitations
The string must not begin with <SPACE> <TAB> <0xFF> =
because SET /P is used to write without trailing CRLF.
#dbenham mentioned the undocumented verbs of CERTUTIL. The type 0x40000001 of the CryptBinaryToStringA function is documented as:
Do not append any new line characters to the encoded string. The default behavior is to use a carriage return/line feed (CR/LF) pair (0x0D/0x0A) to represent a new line.
Windows Server 2003 and Windows XP: This value is not supported.
Optimal, reliable ... with Powershell. However, there are some limitations in the length of the text.
Unicode
#echo off
set "string=Everything will be fine"
for /f "tokens=* delims=" %%i in ('powershell [convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes("""%string%"""^)^)') do set "encoded=%%i"
echo %encoded%
UTF8
#echo off
set "string=Everything will be fine"
for /f "tokens=* delims=" %%i in ('powershell [convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("""%string%"""^)^)') do set "encoded=%%i"
echo %encoded%
I need to make a batch file for my groupmates (actually, I need to make a sequence of the program, but for simple to ask, I use batch file).
The batch's job is copy a specific file in their computer to the batch's folder. But the problem is I don't know the path to that file of all my groupmates.
Here are the things I need:
Help my groupmates choose their path to that file. (Maybe just auto-find that file in their computers).
Copy that file and paste it into the batch file's folder (which include my other programs).
After all my other programs finished their job, copy and replace that file to its original folder.
Do you have any script that might help?
You can start with this batch code :
#echo off
Title Search for a file by name (Wildcard accepted) by Hackoo 2014
mode con cols=90 lines=5 & color 9B
echo(
Set /p "FileName=Please Enter the name of the file to find (Wildcard accepted) : "
echo(
Set Tmp=Tmp.txt
Set SearchResult=SearchResult.txt
Call :BrowseFolder "Select the Source folder" "C:\Program"
Set LocationFolder=%MyFolder%
echo You chose to looking into "%LocationFolder%" for this file "%FileName%"
echo( & cls & Color 0A
echo( & echo Please Wait for moment .... Searching for "%FileName%" on "%LocationFolder%"
Where /r "%LocationFolder%" "%FileName%" > %Tmp%
Cmd /U /C Type %Tmp% > %SearchResult%
Del %Tmp%
Start %SearchResult%
::******************************************************************************
:BrowseFolder
set MyFolder=
set vbs="%temp%\_.vbs"
set cmd="%temp%\_.cmd"
for %%f in (%vbs% %cmd%) do if exist %%f del %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
>%vbs% echo set WshShell=WScript.CreateObject("WScript.Shell")
>>%vbs% echo set shell=WScript.CreateObject("Shell.Application")
>>%vbs% echo set f=shell.BrowseForFolder(0,%1,0,%2)
>>%vbs% echo if typename(f)="Nothing" Then
>>%vbs% echo wscript.echo "set MyFolder=Dialog Cancelled"
>>%vbs% echo WScript.Quit(1)
>>%vbs% echo end if
>>%vbs% echo set fs=f.Items():set fi=fs.Item()
>>%vbs% echo p=fi.Path:wscript.echo "set MyFolder=" ^& p
cscript //nologo %vbs% > %cmd%
for /f "delims=" %%a in (%cmd%) do %%a
for %%f in (%vbs% %cmd%) do if exist %%f del %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
::******************************************************************************
EDIT : 28/06/2015 at 07:00
#echo off
Title Search for a file by name and copy it (Wildcard accepted) by Hackoo 2015
mode con cols=90 lines=5 & color 9B
Set /p "FileName=Please Enter the name of the file to find (Wildcard accepted) : "
Set SearchResult=SearchResult.txt
Call :BrowseFolder "Select the Source folder" "C:\Program"
Set LocationFolder=%MyFolder%
echo You chose to looking into "%LocationFolder%" for this file "%FileName%"
echo( & cls & Color 0A
echo( & echo Please Wait for moment .... Searching for "%FileName%" on "%LocationFolder%"
where /r "%LocationFolder%" "%FileName%" > %SearchResult%
Goto:CopyMyFile
::******************************************************************************
:BrowseFolder
set MyFolder=
set vbs="%temp%\_.vbs"
set cmd="%temp%\_.cmd"
for %%f in (%vbs% %cmd%) do if exist %%f del %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
>%vbs% echo set WshShell=WScript.CreateObject("WScript.Shell")
>>%vbs% echo set shell=WScript.CreateObject("Shell.Application")
>>%vbs% echo set f=shell.BrowseForFolder(0,%1,0,%2)
>>%vbs% echo if typename(f)="Nothing" Then
>>%vbs% echo wscript.echo "set MyFolder=Dialog Cancelled"
>>%vbs% echo WScript.Quit(1)
>>%vbs% echo end if
>>%vbs% echo set fs=f.Items():set fi=fs.Item()
>>%vbs% echo p=fi.Path:wscript.echo "set MyFolder=" ^& p
cscript //nologo %vbs% > %cmd%
for /f "delims=" %%a in (%cmd%) do %%a
for %%f in (%vbs% %cmd%) do if exist %%f del %%f
for %%g in ("vbs cmd") do if defined %%g set %%g=
::******************************************************************************
:CopyMyFile
Cls
for /f "delims=*" %%a in (%SearchResult%) do (echo Copy "%%a" "%~dp0" & Copy "%%a" "%~dp0")
Pause
dir c:\nameoffiletosearch /s /b > %temp%\results.txt will create a list with full path of all occurences of your file in drive c.
You could even wrap this in a loop that searches multiple drives.
Then get the path from the results.txt and use it with your copy command.
I am looking for help on creating a batch script which:
Asks for an input line(maybe a few words, may include wildcards, maybe just a keyword)
Goes through all the csv/xls files in a folder
Extracts the rows where that input line is found
Puts the results into a new workbook
Any help please would be great,
would love if the file is also annotated so i can learn to
Thank you in advance
#Echo OFF
#IF "%_Echo%" NEQ "" Echo %_Echo%
Echo xls file filter - select lines ending with the requested extension type
Echo v1.1
If "%1" NEQ "" goto -Process
Echo.
Echo Parameters
Echo 1 - Extension to search for
Echo.
Echo .csv Files in C:\Users\test\Desktop\output will be scanned for the input
Echo All matching extensions found in folder C:\Users\test\Desktop\output\*.csv
Echo Where ********* is the filteryou entered.
Echo.
Pause
Set /p _b= "Enter Extension "
if "%_b%" NEQ "" goto -Process2
Goto :EOF
:-Process
Set _b=%1
:-Process2
Set _Src="C:\Users\test\Desktop\output"
Echo Source %_Src% Files 20yy-mm-dd.csv
Set _TFN="C:\Users\test\Desktop\Files\%_b%.csv"
Echo Filtered File: %_TFN%
set _HDR=
set _cnt=0
Pushd %_src%
::dir /b "C:\Users\test\Desktop\output\*.csv"
FOR /F "usebackq tokens=1,2*" %%a IN (`dir /b "C:\Users\test\Desktop\output\**********.csv"`) DO Call :-FilterFl %%a
Echo %_cnt% Files processed
popd
pause
Goto :EOF
:-FilterFl
::Echo 1-%1 2-%2
if not exist %1 goto :-NF
if "%_HDR%" NEQ "Done" call :-DoHdr %1
Echo Processing %1
FIND /i "%_b%"<%1 >>%_TFN%
set /a _cnt=_cnt + 1
Goto :EOF
:-NF
Echo %1 is not found
goto :EOF
:-DoHdr
if "%_Debug%" NEQ "" Echo -DoHdr %1
FIND "---," <%1 >%_TFN%
set _HDR=Done
goto :EOF
echo The error level is: %ERRORLEVEL%
Produces
>The error level is: 15
What I would like:
>The error level is: F
do I need to do conversions or is there a way to display numbers differently?
Any help in the right direction is appreciated, thanks.
It was a long time ago, I was very bored.
cmdcalc.cmd
#echo off
if not defined trace set trace=rem
%trace% on
SetLocal
if "%1"=="/?" (
call :help %0
goto :eof
)
Set MinInBase=
if /i "%2" EQU "Bin" call :DoBin %1
if /i "%2" EQU "Hex" call :DoHex %1
If not defined BinStr call :DoDec %1
EndLocal & set RET=%RET%
goto :eof
:DoBin
Set MinInBase=2
Set ShiftBy=1
Set StartSyn=0b
call :DoCalc %1
goto :eof
:DoHex
Set MinInBase=16
Set ShiftBy=4
Set StartSyn=0x
call :DoCalc %1
goto :eof
:DoDec
if {%1} EQU {} goto :eof
set /a BinStr=%1
set RET=%BinStr%
echo %RET%
goto :eof
:DoCalc
Set BinStr=
SET /A A=%1
%Trace% %A%
:StartSplit
SET /A B="A>>%ShiftBy%"
%Trace% %B%
SET /A C="B<<%ShiftBy%"
%Trace% %C%
SET /A C=A-C
%Trace% %C%
call :StringIt %C%
If %B% LSS %MinInBase% goto :EndSplit
set A=%B%
goto :StartSplit
:EndSplit
call :StringIt %B%
set RET=%StartSyn%%BinStr%
Echo %RET%
EndLocal & set RET=%RET%
goto :eof
:StringIt
set Bin=0123456789ABCDEF
FOR /F "tokens=*" %%A in ('echo "%%BIN:~%1,1%%"') do set RET=%%A
set ret=%ret:"=%
Set BinStr=%Ret%%BinStr%
goto :eof
:help
echo %1 syntax:
echo.
echo %1 Calculation [Hex^|Bin]
echo.
echo eg %1 12*2 Hex
echo.
echo gives 0x18.
goto :eof
According to the external resource Windows Environment Variables, there is an undocumented built-in read-only variable =ExitCode which returns the current exit code in hexadecimal format. To ensure the ErrorLevel value equals the exit code, use cmd /C exit %ErrorLevel%.
So if you are using this line code...:
cmd /C exit %ErrorLevel%
echo The error level is: %=ExitCode%
...you will receive this (supposing the ErrorLevel is 15):
The error level is: 0000000F
To get rid of the leading zeros, use this...:
cmd /C exit %ErrorLevel%
for /F "tokens=* delims=0" %%Z in ("%=ExitCode%") do set "HEXCODE=%%Z"
if not defined HEXCODE set "HEXCODE=0"
echo The error level is: %HEXCODE%
...to get this:
The error level is: F
Just write it in vbscript instead of batch
put the vbscript statement below into a file.
WScript.Echo Hex( WScript.Arguments(0) )
then to run it, simple type this on the command line ( in a batch script, use a for loop to capture the value if required )
C:\workspace> cscript //nologo hex.vbs 15
F
There is no need to install anything. vbscript comes by default in most windows systems.
perl -e"printf qq{The errorlevel is: %X\n}, $ENV{ERRORLEVEL}"
Requires Perl to be installed, of course, but that's easy to do.