Tech Support Guy
TheOutcaste's Avatar
TheOutcaste TheOutcaste is offline
Computer Specs
Member with 9,028 posts.
Join Date: Aug 2007
Location: Oregon, USA
Experience: Intermediate
05-May-2009, 08:32 PM #7
More than a couple of bugs. Just shows I didn't test it with all of the characters in all possible combinations.
The problem here is the " you entered, which is before the < and > symbols. This matches with the first double quote, so the rest of the line is considered unquoted, so any special characters are actually processed.
So need to remove any quotes first, rather than the !. Since the line gets quoted at that point, we don't need to worry about the ! being seen as the start of a variable, and can remove it once the other special characters are removed.

Found out it won't remove a , or ? as well as the ; either.
The ; and , are seen as delimiters by the first For loop, so never get processed. Seems I forgot that and obviously didn't test with those.
The For loop is actually expecting a filename, so the ? is treated as a wildcard character, so it searches the current directory for a file with a single character filename. If you don't have a file with a single character as a name in the current directory, it just gets skipped. If you do have such a file, say a file named a, it would remove the letter a from the entered folder name. So that wouldn't be good.
Same thing would happen with the *, except it would match all files in the current directory. (This could be used to make sure the folder name entered does not contain the name of any files (including extension) in the current directory)
So just need to move those characters to the 2nd For loop.

And if you don't enter any valid characters, it won't remove ~ = * ; , ?, so I added a check for that.

So give this a try and see if you can find any more bugs:

SET /P folder=Folder Name:
Set folder="%folder:"=%"
Setlocal EnableDelayedExpansion
For %%I In (^| ^& ^< ^> ^^ + ^( ^) \ / . @ # $ { } [ ] ' : ` ^%% ^") Do Set folder=!folder:%%I=!
:: Now remove any !
SetLocal DisableDelayedExpansion
Set folder="%folder:!=%"
EndLocal&Set folder=%folder:~1,-1%
Set _Flag1=
For /F "Tokens=1* Delims=~=*;,?" %%J In ('Echo !folder!') Do (
Set folder=%%J%%K
Set _Flag1=%%J
Set _Flag2=%%K
If NOT "%_Flag2%"=="" Goto _parse
If Not Defined _Flag1 Echo None of the characters you entered are valid. Please try again&Goto _GetName
:: Now revert to previous settings. The Set is needed to pass the
:: Folder variable back to the previous environment
EndLocal&Set folder=%folder%
Echo You said your folder name will be %folder%.
And to remove the surrounding quotes so they aren't displayed, use this:
Echo %~1
See Call /? (or For /?) for an explanation of the parameter modifiers. Unfortunately, they only work for loop variables, or command line parameters.