Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Batch Script to Replace Environment Variables in a File

I want to write a batch file that will take the contents of a file, and replace any environment variable references inside the file with the actual environment variable values. Is this possible? Basically, if a file had this:

%PROGRAM FILES%\Microsoft SQL Server\

then I would want the file contents to become:

C:\Program Files\Microsoft SQL Server\

after the batch script ran. This is just one example, but I want ALL environment variables to be expanded. Thanks in advance for any help!

like image 605
skb Avatar asked Jun 06 '26 06:06

skb


1 Answers

If powershell is present on the system, you could do:

powershell -command "get-content 'input.txt' | foreach { [System.Environment]::ExpandEnvironmentVariables($_) } | set-content -path 'output.txt'"

The following works with a plain batch file, though blank lines are removed from the output

@echo off
goto :start

:expand
echo %~1 >> output.txt
goto:eof

:start
echo. > output.txt
for /f "delims=" %%i in (input.txt) do call:expand "%%i"
like image 76
Oren Trutner Avatar answered Jun 09 '26 00:06

Oren Trutner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!