How to handle file names with &

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Yanta
Posts: 48
Joined: 01 Sep 2019 07:08

How to handle file names with &

#1 Post by Yanta » 16 Sep 2020 21:12

I have a font I want to install called Spirit & Ghost.ttf

The following code processes a list of font files in a folder.

Code: Select all

    SET SRC=%CD:~0,2%
    set SrcPath=%SRC%\PostInstall\%USERNAME%
    
:FONTS
    IF EXIST "%SrcPath%\Fonts\" (
        Echo Installing Custom Fonts
        Echo %time% Installing Custom Fonts >>C:\%USERDOMAIN%.PostInstall.Log 2>&1
        FOR %%a in ("%SrcPath%\Fonts\*.?tf") do call :Installfont "%%~nxa"
        Echo %time% Fonts will not be available until the system has been restarted >>C:\%USERDOMAIN%.PostInstall.Log 2>&1
	)
	Goto SYMLNK

:Installfont
        Set font=%~1
        IF EXIST "%LOCALAPPDATA%\Microsoft\Windows\Fonts\%font%" echo Font %font% already installed. >>C:\%USERDOMAIN%.PostInstall.Log 2>&1
        IF EXIST "%WINDIR%\Fonts\%font%" echo Font %font% already installed. >>C:\%USERDOMAIN%.PostInstall.Log 2>&1
        IF NOT EXIST "%LOCALAPPDATA%\Microsoft\Windows\Fonts\%font%" IF NOT EXIST "%WINDIR%\Fonts\%font%" (
            Set fext=%font:~-3%
            IF /i "%fext%"=="ttf" Set ftype=Truetype
            IF /i "%fext%"=="otf" Set ftype=Opentype
			Echo Installing %font% to "%LOCALAPPDATA%\Microsoft\Windows\Fonts" >>C:\%USERDOMAIN%.PostInstall.Log 2>&1
            Echo Processing font %font% Extension: %fext% Type: "(%ftype%)" >>C:\%USERDOMAIN%.PostInstall.Log 2>&1
			copy "%SrcPath%\Fonts\%font%" "%LOCALAPPDATA%\Microsoft\Windows\Fonts\%font%" /y >>C:\%USERDOMAIN%.PostInstall.Log 2>&1
            REG ADD "HKCU\Software\Microsoft\Windows NT\CurrentVersion\Fonts" /v "%font% (%ftype%)" /d "%LOCALAPPDATA%\Microsoft\Windows\Fonts\%font%" /t REG_SZ /f >>C:\%USERDOMAIN%.PostInstall.Log 2>&1
        )
        exit /b

:SYMLNK 
	Echo Finished
Of course, this fails when it hits the spirit & ghost.ttf file...

Code: Select all

'GHOST.ttf' is not recognized as an internal or external command,
operable program or batch file.
How do I handle file names with & in them?

OJBakker
Expert
Posts: 88
Joined: 12 Aug 2011 13:57

Re: How to handle file names with &

#2 Post by OJBakker » 17 Sep 2020 04:43

protect set variable from special characters by using double quotes.
change

Code: Select all

set var=value
to

Code: Select all

set "var=value"
protect echo variable from special characters by using double quotes.
change

Code: Select all

echo %var% 
to

Code: Select all

echo "%var%"
The quotes will be visible in the output.
If you don't want visible quotes you will have to escape the special characters in the value of the variable before using echo.

Yanta
Posts: 48
Joined: 01 Sep 2019 07:08

Re: How to handle file names with &

#3 Post by Yanta » 17 Sep 2020 20:18

Thanks

Post Reply