1

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.

Neumy
  • 21
  • 1
  • The `%` is already consumed by the `cmd` interpreter at run time. Why on earth does your directories contain special characters? – Gerhard May 02 '22 at 06:27
  • You have [delayed variable expansion](https://ss64.com/nt/delayedexpansion.html) enabled, haven't you? – aschipfl May 02 '22 at 09:42
  • I recommend to read also [Why is no string output with 'echo %var%' after using 'set var = text' on command line?](https://stackoverflow.com/a/26388460/3074564) Do not use `set str="DirectoryName%"`, but use `set "str=DirectoryName%"` whereby in a batch file `%` must be escaped with one more `%` to get it interpreted as literal character. So there must be used `set "str=DirectoryName%%"`. It could be that even more escapes are necessary depending on how often the string is parsed by `cmd.exe` before execution of the command line with the string `DirectoryName%`. – Mofi May 02 '22 at 10:00
  • You have to use next `pushd "%str%"` which should work as expected even with delayed expansion enabled at top of the batch script although most likely not needed at all. – Mofi May 02 '22 at 10:03
  • But I don't understand what should be the problem on environment variable `USERPROFILE` with the full path to the current user´s profile directory (also known as HOME directory which is the name on Linux/Mac for the user´s main directory because of `/home/username` instead of `%SystemDrive%\Users\UserName` as on Windows) should be a problem on processing it. A well coded batch file does not have ever a problem with a folder path like `C:\Temp\ Development & Test(!)_%_Folder'`. Only not well coded batch files do not work with such a folder path with two leading spaces and some special chars. – Mofi May 02 '22 at 10:12
  • Does this answer your question? [Ignore percent sign in batch file](https://stackoverflow.com/questions/1907057/ignore-percent-sign-in-batch-file) – phuclv May 02 '22 at 10:41

0 Answers0