Monday, December 18, 2017

windows 7 - Why does CMD substring not work when BAT called from SENDTO?

I wrote a BAT file to strip a leading '@' off a filename. (Please don't ask why! ...why Windows, why CMD...) :)


Here's the BAT file:


IF EXIST "%~1" (
FOR /F %%F IN ("%~1") DO (
CD /D "%%~dpF"
IF ERRORLEVEL 1 (
ECHO. Failed to CD to folder: %%~dpF
) ELSE (
SETLOCAL ENABLEEXTENSIONS
SET A=%%~nxF
IF "%A:~0,1%"=="@" (
ECHO. RENAME "%A%" "%A:~1%"
RENAME "%A%" "%A:~1%"
REM RENAME "%%A%" "%%A:~1%"
) ELSE (
ECHO. File does not start with @: %A%
)
ENDLOCAL
)
)
) ELSE (
ECHO. File not found: %1
)
pause

When I run it from the command line in a DOS window, it seems to work:


18:54:04.97>dir /b *foo*
@foo.txt
18:54:07.97>test@ "%cd%\@foo.txt"
18:54:18.75>IF EXIST "C:\Users\me\lbin\@foo.txt" (FOR /F %F IN ("C:\Users\me\lbin\@foo.txt") DO (
CD /D "%~dpF"
IF ERRORLEVEL 1 (ECHO. Failed to CD to folder: %~dpF ) ELSE (
SETLOCAL ENABLEEXTENSIONS
SET A=%~nxF
IF "@" == "@" (
ECHO. RENAME "@foo.txt" "foo.txt"
RENAME "@foo.txt" "foo.txt"
REM RENAME "%Afoo.txt"
) ELSE (ECHO. File does not start with @: @foo.txt )
ENDLOCAL
)
) ) ELSE (ECHO. File not found: "C:\Users\me\lbin\@foo.txt" )
18:54:18.77>(
CD /D "C:\Users\me\lbin\"
IF ERRORLEVEL 1 (ECHO. Failed to CD to folder: C:\Users\me\lbin\ ) ELSE (
SETLOCAL ENABLEEXTENSIONS
SET A=@foo.txt
IF "@" == "@" (
ECHO. RENAME "@foo.txt" "foo.txt"
RENAME "@foo.txt" "foo.txt"
REM RENAME "%Afoo.txt"
) ELSE (ECHO. File does not start with @: @foo.txt )
ENDLOCAL
)
)
RENAME "@foo.txt" "foo.txt"
18:54:18.80>pause
Press any key to continue . . .
18:54:20.74>

but when I run the BAT file from a shortcut in the SENDTO menu, the substring operation doesn't expand correctly - specifically, the "IF" doesn't expand right (IF "%A:~0,1%"=="@" () - see?...


C:\Users\me\lbin>IF EXIST "C:\Users\me\lbin\@foo.txt" (FOR /F %F IN ("C:\Users\me\lbin\@foo.txt") D
O (
CD /D "%~dpF"
IF ERRORLEVEL 1 (ECHO. Failed to CD to folder: %~dpF ) ELSE (
SETLOCAL ENABLEEXTENSIONS
SET A=%~nxF
IF "~0,1" == "@" (
ECHO. RENAME "" "~1"
RENAME "" "~1"
REM RENAME "%A~1"
) ELSE (ECHO. File does not start with @: )
ENDLOCAL
)
) ) ELSE (ECHO. File not found: C:\Users\me\lbin\@foo.txt )
C:\Users\me\lbin>(
CD /D "C:\Users\me\lbin\"
IF ERRORLEVEL 1 (ECHO. Failed to CD to folder: C:\Users\me\lbin\ ) ELSE (
SETLOCAL ENABLEEXTENSIONS
SET A=@foo.txt
IF "~0,1" == "@" (
ECHO. RENAME "" "~1"
RENAME "" "~1"
REM RENAME "%A~1"
) ELSE (ECHO. File does not start with @: )
ENDLOCAL
)
)
File does not start with @:
C:\Users\me\lbin>pause
Press any key to continue . . .

Ideas?

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...