C:\>teststrlen This string is 22 long
Code: Select all
@echo off
call :loadMacros
set "myVar=%*"
%$Strlen% myVar result
echo %myvar% is %result% characters long
exit /b
:loadMacros
set LF=^
::Above 2 blank lines are required - do not remove
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
:::: StrLen String Result
set $StrLen=for %%n in (1 2) do if %%n==2 (%\n%
for /F "tokens=1,2 delims=, " %%1 in ("!argv!") do (%\n%
set "str=A!%%~1!"%\n%
set "len=0"%\n%
for /l %%A in (12,-1,0) do (%\n%
set /a "len|=1<<%%A"%\n%
for %%B in (!len!) do if "!str:~%%B,1!"=="" set /a "len&=~1<<%%A"%\n%
)%\n%
for %%v in (!len!) do endlocal^&if "%%~b" neq "" (set "%%~2=%%v") else echo %%v%\n%
) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,
exit /b
Fine, it works great. Notice no setlocal statements in the code. Then at the command line:
C:\>teststrlen This string is 22 long
C:\>This string is 22 long is 22 characters long
C:\>set myvar
C:\>myvar=This string is 22 long
C:\>set result
C:\>result=22
Ok fine, so now %$Strlen% is a defined macro available at the command line:
C:\>set $Strlen
displays the macro in all its glory
so try using it from the command line and it bombs:
C:\>%$Strlen% myvar length
...
...etc
C:\>(
set /a "len|=1<<1"
for %B in (!len!) do if "!str:~%B,1!" == "" set /a "len&=~1<<1"
)
8190
C:\>if "!str:~!len!,1!" == "" set /a "len&=~1<<1"
C:\>(
set /a "len|=1<<0"
for %B in (!len!) do if "!str:~%B,1!" == "" set /a "len&=~1<<0"
)
8191
C:\>if "!str:~!len!,1!" == "" set /a "len&=~1<<0"
C:\>endlocal & if "%~b" NEQ "" (set "=!len!" ) else echo !len!
The syntax of the command is incorrect.
=============
at this line of code:
for %%v in (!len!) do endlocal^&if "%%~b" neq "" (set "%%~2=%%v") else echo %%v%\n%
%~2 should be 'length' but it is undefined, as is 'myvar'
with 'len' equal to 8191 at that point. len started at 4096 and went up from there.
So why should it work fine from a batch file and not at the command line?