'Windows Batch: Using a % in a Variable

I'm struggling here ...

Let's say I have this scenario/code:

set str="DirectoryName%"
echo %str%
pushd %str%
OUTPUT:
"DirectoryName"
The system cannot find the path specified.

The script I have looks through a "HOME" directory and outputs the name and directory-size. (Works well ... until ...) I have some users that are putting "special characters" into their directory names. Currently it's only % ... but it's screwing everything up and I'm struggling to find a solution (and I can't tell them NOT to).

One potential solution is to do a "replace" and add another %.

set str="DirectoryName%%"
echo %str%
pushd %str%
OUTPUT:
"DirectoryName%"
...proceed to the directory...

But I can't seem to figure out how to do the replace command. As the % is gone before the command is run.

set str=!str:%%=%%%%!

Does anyone have any solution for this? And I haven't even started looking into other "special characters".

Thanks for the help.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source