开发者

Windows Batch Script to Replace Environment Variables in a File

开发者 https://www.devze.com 2023-01-01 19:52 出处:网络
I want to write a batch file that will take the contents of a file, and replace any environment variable refe开发者_开发问答rences inside the file with the actual environment variable values.Is this p

I want to write a batch file that will take the contents of a file, and replace any environment variable refe开发者_开发问答rences 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!


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消