代码之家  ›  专栏  ›  技术社区  ›  skb

用于替换文件中环境变量的Windows批处理脚本

  •  3
  • skb  · 技术社区  · 15 年前

    我想编写一个批处理文件,它将获取文件的内容,并用实际的环境变量值替换文件中的任何环境变量引用。这可能吗?基本上,如果一个文件有:

    %PROGRAM FILES%\Microsoft SQL Server\
    

    然后我希望文件内容变成:

    C:\Program Files\Microsoft SQL Server\
    

    批处理脚本运行后。这只是一个例子,但我希望扩展所有环境变量。提前感谢您的帮助!

    1 回复  |  直到 15 年前
        1
  •  2
  •   Oren Trutner    15 年前

    如果系统上存在PowerShell,则可以执行以下操作:

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

    虽然从输出中删除了空白行,但以下操作可用于普通批处理文件

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