如何在REG文件中替换固定路径为当前文件夹路径?
Since registry files don’t support dynamic path variables directly like batch scripts do, you can’t use things like %~dp0 directly in a .reg file. Instead, you need to generate the registry entry dynamically using a batch script that captures the current folder path and writes it to a temporary .reg file for import. Here are the best ways to do this:
Method 1: Use a Batch Script to Generate & Import the Registry Entry
This is the most portable solution—perfect if you plan to move the folder to different locations. Create a new batch file (e.g., SetupRunScript.bat) in the same folder as your test.bat, then paste this code:
@echo off setlocal enabledelayedexpansion rem Grab the full path to test.bat (current folder + test.bat) set "targetBat=%~dp0test.bat" rem Escape backslashes for the registry file (REG requires double backslashes) set "escapedBat=!targetBat:\=\\!" rem Create the dynamic registry file echo Windows Registry Editor Version 5.00 > TempRunScript.reg echo [HKEY_CLASSES_ROOT\*\shell\Run script] >> TempRunScript.reg echo @="Run &script" >> TempRunScript.reg echo [HKEY_CLASSES_ROOT\*\shell\Run script\command] >> TempRunScript.reg echo @="\"%escapedBat%\" \"%%1\"" >> TempRunScript.reg rem Import the registry entry silently regedit /s TempRunScript.reg echo Successfully added the "Run script" context menu with the current folder path! rem Optional: Clean up the temporary reg file del TempRunScript.reg pause
Breakdown of how this works:
%~dp0automatically fetches the full path of the folder where the batch script lives (including the trailing backslash).- We convert single backslashes to double backslashes (
\\) because registry files require escape characters for file paths. - The script generates a temporary
.regfile with the correct dynamic path, then imports it silently usingregedit /s. - It cleans up the temporary file afterward to avoid clutter.
Method 2: Manual Update (Not Recommended for Portability)
If you only need this on one machine and don’t plan to move the folder, you can manually edit the .reg file each time you relocate it:
- Open the
.regfile in a text editor. - Replace
C:\Users\teodora\Desktop\test.batwith the new full path to yourtest.bat. - Save the file and re-import it by double-clicking.
This is a quick fix but not ideal if you need to move the folder regularly—stick with Method 1 for portability.
内容的提问来源于stack exchange,提问作者Alexandra Giurgiteanu

