How can I detect the drive letter of a booted USB drive from script? - deployment

I'm launching WinPE 2 from a bootable UFD, and I need to detect the drive letter in order to tell ImageX where to find the WIM. However, depending on the machine I'm imaging, there are different mounted drives.
I need a way to consistently mount the UFD at, say, P: or something. Is there a way to detect the letter of the drive from which the machine was booted, or another way to pass the location of my WIM file to a variable accessible from startnet.cmd?
Here's someone else with the same issue over at TechNet.
http://social.technet.microsoft.com/Forums/en-US/itprovistadeployment/thread/3e8bb8db-a1c6-40be-b4b0-58093f4833be?prof=required#

This VBScript will show a message for each removable drive (letter:description), could be easily modified to search for a particular drive and return the letter.
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk where MediaType = 11")
For Each objDisk in colDisks
Wscript.Echo objDisk.DeviceID & objDisk.Description
Next
Don't know if that helps at all.

It's a less generic solution than the others mentioned here, but there appears to be a specific way to determine which underlying volume a "RAM-drive-booted" Windows PE OS was booted from. From the documentation on Windows PE in the Windows Automated Installation Kit:
If you are not booting Windows
Deployment Services, the best way to
determine where Windows PE booted from
is to first check for
PEBootRamdiskSourceDrive registry key.
If it is not present, scan the drives
of the correct PEBootType and look for
some kind of tag file that identifies
the boot drive.
(The registry value in question sits under HKLM\SYSTEM\CurrentControlSet\Control.)

Here's a non-optimal solution. In this case, the UFD has to have a specific name, which is passed to the script which searches every possible drive letter for a match. It's probably not practical to rely on the flash drives all having the same name.
Still hoping someone pops by with a better answer!
setlocal
:: Initial variables
set TMPFILE=%~dp0getdrive.tmp
set driveletters=abcdefghijklmnopqrstuvwxyz
set MatchLabel_res=
for /L %%g in (2,1,25) do call :MatchLabel %%g %*
if not "%MatchLabel_res%"=="" echo %MatchLabel_res%
goto :END
:: Function to match a label with a drive letter.
::
:: The first parameter is an integer from 1..26 that needs to be
:: converted in a letter. It is easier looping on a number
:: than looping on letters.
::
:: The second parameter is the volume name passed-on to the script
:MatchLabel
:: result already found, just do nothing
:: (necessary because there is no break for for loops)
if not "%MatchLabel_res%"=="" goto :eof
:: get the proper drive letter
call set dl=%%driveletters:~%1,1%%
:: strip-off the " in the volume name to be able to add them again further
set volname=%2
set volname=%volname:"=%
:: get the volume information on that disk
vol %dl%: > "%TMPFILE%" 2>&1
:: Drive/Volume does not exist, just quit
if not "%ERRORLEVEL%"=="0" goto :eof
set found=0
for /F "usebackq tokens=3 delims=:" %%g in (`find /C /I "%volname%" "%TMPFILE%"`) do set found=%%g
:: trick to stip any whitespaces
set /A found=%found% + 0
if not "%found%"=="0" set MatchLabel_res=%dl%:
goto :eof
:END
if exist "%TMPFILE%" del "%TMPFILE%"
endlocal

To elaborate reuben's answer in more detail, here is my batch file:
wpeutil UpdateBootInfo
for /f "usebackq skip=1 tokens=3 delims= " %%l in ( `reg query HKLM\System\CurrentControlSet\Control /v PEBootRAMDiskSourceDrive` ) do set "PendrivePath=%%l"
set "PendriveLetter=%PendrivePath:~0,1%"
echo The boot pendrive's drive letter is %PendriveLetter%

Related

according to choice specific line should run in cmd.exe using batch file

I wanted to give this choice
#echo off
echo what operation you wanted to perform
echo a:creating a new web server?
echo or
echo b:Edit root url for already existed web server
set /P var = "What is your option a or b"
if "%var%" == "A" (
cd C:\Program Files\Infor\Mongoose\Tools
infordbcl.exe addwebserver -name:sample -product:Mongoose -rooturl:https://uscovwmongoose3
)
if "%var%" == "B" (
infordbcl.exe addwebserver -name:sample -product:Mongoose -rooturl:https://mongoose.com -
mode:edit
)
I ran this batch file using powershell.
After entering the choice A or B, the commands specified in if blocks are not getting executed in cmd.exe
Is their any syntax errors in it, please let me know
This is how Choice could be used here:
#echo off
Choice /N /C ce /M " <?> (C)reate new Server <?> (E)dit root url for existing web server"
If Errorlevel 2 (
REM If the Change directory command is also meant to execute in this block, remove and place CD command prior to choice command.
infordbcl.exe addwebserver -name:sample -product:Mongoose -rooturl:https://mongoose.com -mode:edit
) Else (
REM confirm if lack of url extension is correct
cd "C:\Program Files\Infor\Mongoose\Tools"
infordbcl.exe addwebserver -name:sample -product:Mongoose -rooturl:https://uscovwmongoose3
)
Explanation:
/N hides the default prompt (whatever keys are defined using /C or the default Y/N if /C is not used)
/C allows definition of keys within the range 0-9 and A-Z
errorlevel for each key is set according to occurance after the /C
switch
for /C ce, c will return Errorlevel 1, e will return errorlevel 2
and so on
/M "string" allows a custom string to be defined to explain the Choice. Encase the string within doublequotes.
When you test the returned Errorlevel
You must test from Highest to Lowest.
This is because the command intepreter reads If Errorlevel n as If Errorlevel n or higher
For more information and usage examples, type choice /? in cmd.exe

Batch Code explanation

I found this code online, and it allows me to choose a folder using a GUI. Can someone please explain to me how this works, and how I can get an output from it. I am hoping I can get an output and assign that to a variable.
NOTE: I did NOT make this. I simply found it online at another stack overflow post.
:: fchooser.bat
:: launches a folder chooser and outputs choice to the console
:: http://stackoverflow.com/a/15885133/1683264
#echo off
setlocal
set "psCommand="(new-object -COM 'Shell.Application')^
.BrowseForFolder(0,'Please choose a folder.',0,0).self.path""
for /f "usebackq delims=" %%I in (`powershell %psCommand%`) do set "folder=%%I"
setlocal enabledelayedexpansion
echo You chose !folder!
endlocal
Thanks a lot,
ChapelCone56
set "psCommand="(new-object -COM 'Shell.Application')^.BrowseForFolder(0,'Please choose a folder.',0,0).self.path""
It is creating a new powershell object for windows to invoke the browse folder dialogue
FOR /F
Loop command against the results of other command.
usebackq
use the different quoting style
powershell %psCommand%
creates a pipileline that another object can use
set "folder=%%I"
setting folder variable to the choosen folder name
echo You chose !folder!
display the choice
if you want to use the selected folder name, use variable folder whose value can be found as !folder!

Use Robocopy to copy only changed files?

I'm trying to find an easy way of deploying only changed files to the webserver for deployment purpose. In times past I've used MSBuild, which could be told to only copy files that were newer than the ones on the target, but I'm in a hurry and don't want to try to figure out the newer version of MSBuild.
Can I use ROBOCOPY for this? There is a list of options for exclusion, which is:
/XC :: eXclude Changed files.
/XN :: eXclude Newer files.
/XO :: eXclude Older files.
/XX :: eXclude eXtra files and directories.
/XL :: eXclude Lonely files and directories.
What exactly does it mean to exclude? Exclude copying, or exclude overwriting? For example, if I wrote:
ROBOCOPY C:\SourceFolder\ABC.dll D:\DestinationFolder /XO
would this copy only newer files, not files of the same age?
Or is there a better tool to do this?
To answer all your questions:
Can I use ROBOCOPY for this?
Yes, RC should fit your requirements (simplicity, only copy what needed)
What exactly does it mean to exclude?
It will exclude copying - RC calls it skipping
Would the /XO option copy only newer files, not files of the same age?
Yes, RC will only copy newer files. Files of the same age will be skipped.
(the correct command would be robocopy C:\SourceFolder D:\DestinationFolder ABC.dll /XO)
Maybe in your case using the /MIR option could be useful. In general RC is rather targeted at directories and directory trees than single files.
You can use robocopy to copy files with an archive flag and reset the attribute. Use /M command line, this is my backup script with few extra tricks.
This script needs NirCmd tool to keep mouse moving so that my machine won't fall into sleep. Script is using a lockfile to tell when backup script is completed and mousemove.bat script is closed. You may leave this part out.
Another is 7-Zip tool for splitting virtualbox files smaller than 4GB files, my destination folder is still FAT32 so this is mandatory. I should use NTFS disk but haven't converted backup disks yet.
backup-robocopy.bat
#REM https://technet.microsoft.com/en-us/library/cc733145.aspx
#REM http://www.skonet.com/articles_archive/robocopy_job_template.aspx
set basedir=%~dp0
del /Q %basedir%backup-robocopy-log.txt
set dt=%date%_%time:~0,8%
echo "%dt% robocopy started" > %basedir%backup-robocopy-lock.txt
start "Keep system awake" /MIN /LOW cmd.exe /C %basedir%backup-robocopy-movemouse.bat
set dest=E:\backup
call :BACKUP "Program Files\MariaDB 5.5\data"
call :BACKUP "projects"
call :BACKUP "Users\Myname"
:SPLIT
#REM Split +4GB file to multiple files to support FAT32 destination disk,
#REM splitted files must be stored outside of the robocopy destination folder.
set srcfile=C:\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile=%dest%\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile2=%dest%\non-robocopy\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
IF NOT EXIST "%dstfile%" (
IF NOT EXIST "%dstfile2%.7z.001" attrib +A "%srcfile%"
dir /b /aa "%srcfile%" && (
del /Q "%dstfile2%.7z.*"
c:\apps\commands\7za.exe -mx0 -v4000m u "%dstfile2%.7z" "%srcfile%"
attrib -A "%srcfile%"
#set dt=%date%_%time:~0,8%
#echo %dt% Splitted %srcfile% >> %basedir%backup-robocopy-log.txt
)
)
del /Q %basedir%backup-robocopy-lock.txt
GOTO :END
:BACKUP
TITLE Backup %~1
robocopy.exe "c:\%~1" "%dest%\%~1" /JOB:%basedir%backup-robocopy-job.rcj
GOTO :EOF
:END
#set dt=%date%_%time:~0,8%
#echo %dt% robocopy completed >> %basedir%backup-robocopy-log.txt
#echo %dt% robocopy completed
#pause
backup-robocopy-job.rcj
:: Robocopy Job Parameters
:: robocopy.exe "c:\projects" "E:\backup\projects" /JOB:backup-robocopy-job.rcj
:: Source Directory (this is given in command line)
::/SD:c:\examplefolder
:: Destination Directory (this is given in command line)
::/DD:E:\backup\examplefolder
:: Include files matching these names
/IF
*.*
/M :: copy only files with the Archive attribute and reset it.
/XJD :: eXclude Junction points for Directories.
:: Exclude Directories
/XD
C:\projects\bak
C:\projects\old
C:\project\tomcat\logs
C:\project\tomcat\work
C:\Users\Myname\.eclipse
C:\Users\Myname\.m2
C:\Users\Myname\.thumbnails
C:\Users\Myname\AppData
C:\Users\Myname\Favorites
C:\Users\Myname\Links
C:\Users\Myname\Saved Games
C:\Users\Myname\Searches
:: Exclude files matching these names
/XF
C:\Users\Myname\ntuser.dat
*.~bpl
:: Exclude files with any of the given Attributes set
:: S=System, H=Hidden
/XA:SH
:: Copy options
/S :: copy Subdirectories, but not empty ones.
/E :: copy subdirectories, including Empty ones.
/COPY:DAT :: what to COPY for files (default is /COPY:DAT).
/DCOPY:T :: COPY Directory Timestamps.
/PURGE :: delete dest files/dirs that no longer exist in source.
:: Retry Options
/R:0 :: number of Retries on failed copies: default 1 million.
/W:1 :: Wait time between retries: default is 30 seconds.
:: Logging Options (LOG+ append)
/NDL :: No Directory List - don't log directory names.
/NP :: No Progress - don't display percentage copied.
/TEE :: output to console window, as well as the log file.
/LOG+:c:\apps\commands\backup-robocopy-log.txt :: append to logfile
backup-robocopy-movemouse.bat
#echo off
#REM Move mouse to prevent maching from sleeping
#rem while running a backup script
echo Keep system awake while robocopy is running,
echo this script moves a mouse once in a while.
set basedir=%~dp0
set IDX=0
:LOOP
IF NOT EXIST "%basedir%backup-robocopy-lock.txt" GOTO :EOF
SET /A IDX=%IDX% + 1
IF "%IDX%"=="240" (
SET IDX=0
echo Move mouse to keep system awake
c:\apps\commands\nircmdc.exe sendmouse move 5 5
c:\apps\commands\nircmdc.exe sendmouse move -5 -5
)
c:\apps\commands\nircmdc.exe wait 1000
GOTO :LOOP
Looks like /e option is what you need, it'll skip same files/directories.
robocopy c:\data c:\backup /e
If you run the command twice, you'll see the second round is much faster since it skips a lot of things.

Robocopy | Mirror Destination Including Source Parent Folder

I've been trying to put together a robocopy CMD script to be able to ask the user for a path (copy paste or just entering it manually) but I seem to be stumped...
Here's the current code I have;
#ECHO OFF
SETLOCAL
:Input
SET /P "source=Please enter or paste the location you want backed up and press ^<Enter^>."
IF "%source%"=="" GOTO Error
GOTO :DoTask
:Error
ECHO You did not specify a location to be backed up! Please try again. & goto :Input
::SET source="":: Obsolete for now, since user input is possible.
:DoTask
REM SET YEAR
set YEAR=%date:~6,4%
REM SET MONTH
set MONTH=%date:~3,2%
if %MONTH% LSS 10 set MONTH=%MONTH:~1,2%
if %MONTH% LSS 10 set MONTH=0%MONTH%
REM SET DAY
set DAY=%date:~0,2%
if %DAY% LSS 10 set DAY=%DAY:~1,2%
if %DAY% LSS 10 set DAY=0%DAY%
REM SET HOUR
set HOUR=%time:~0,2%
if %HOUR% LSS 10 set HOUR=%HOUR:~1,2%
if %HOUR% LSS 10 set HOUR=0%HOUR%
REM SET MINUTE
set MINUTE=%time:~3,2%
if %MINUTE% LSS 10 set MINUTE=%MINUTE:~1,2%
if %MINUTE% LSS 10 set MINUTE=0%MINUTE%
REM SET SECOND
set SECOND=%time:~6,2%
if %SECOND% LSS 10 set SECOND=%SECOND:~1,2%
if %SECOND% LSS 10 set SECOND=0%SECOND%
SET destination="Backups"\%date%
SET logdir="Backups\Logs"\%date%
SET log="Backups\Logs"\%date%\%HOUR%_%MINUTE%_%SECOND%.log
mkdir "%logdir%" 2>NUL
SET copyoptions=/COPYALL /E /ZB /SEC /MIR
:: /COPYALL :: COPY ALL file info.
:: /E :: Copy Subfolders, including Empty Subfolders.
:: /ZB :: Use restartable mode; if access denied use Backup mode.
:: /SEC :: Copy files with SECurity.
:: /MIR :: MIRror a directory tree.
SET logoptions=/R:0 /W:0 /LOG:%log% /TS /NP /V /ETA /TIMFIX /SECFIX /TEE
:: /R:n:: Number of Retries.
:: /W:n:: Wait time between retries.
:: /LOG:: Output log file.
:: /TS :: Include Source file Time Stamps in the output.
:: /NP :: No Progress - don’t display % copied.
:: /V :: Produce Verbose output log, showing skipped files.
:: /ETA:: Show Estimated Time of Arrival of copied files.
:: /TIMFIX :: FIX file TIMes on all files, even skipped files.
:: /SECFIX :: FIX file SECurity on all files, even skipped files.
:: /TEE:: Output to console window, as well as the log file.
:: /NFL:: No file logging.
:: /NDL:: No dir logging.
ROBOCOPY %source% %destination% %copyoptions% %logoptions%
:End
If this is too long, please feel free to edit this post and just link to it: http://pastebin.com/Np8wBF5b
So basically my issue with the above is as follows;
If I try to enter the path:
C:\Users\Public\Pictures\Sample Pictures
I get the error:
ERROR: Invalid Parameter #3 : "Backups\2013/10/22"
Source: C:\Users\Public\Pictures\Sample\
Destination: G:\Pictures
Notice how the destination in the first line of the error has forward slashes instead of backslashes? But what I find break it is the space between "Sample" and "Pictures".
For if I use a single word, it works perfectly, but brings me to my second problem;
Source: C:\Users\User\Pictures\BlackBerry\
Destination: G:\Backups\2013\10\22\
The source is correct, however in the destination folder it doesn't recreate the "Blackberry" folder, only the contents therein, and that is my issue...
For the user gets to choose multiple destinations to XCOPY, yet all that will happen is all the files get bunched together, with no folder structure etc...
My head is blown with trying to figure this all out, so I am REALLY hoping so kind soul will be able to help me out with this! :)
Enclose %source% in quotes, either there or where it is set.
Robocopy "%source%" ...
Edit: extra code after further the comments
Change this line as shown below: SET destination="Backups"\%date%
for %%a in ("%source%") do SET destination="Backups\%date%\%%~nxa"
The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in XP Pro and higher. Run the batch file below to see the variables, and you can modify them too.
#echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

How to launch Windows' RegEdit with certain path?

How do I launch Windows' RegEdit with certain path located, like "HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0", so I don't have to do the clicking?
What's the command line argument to do this? Or is there a place to find the explanation of RegEdit's switches?
Use the following batch file (add to filename.bat):
REG ADD HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit /v LastKey /t REG_SZ /d Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Veritas\NetBackup\CurrentVersion\Config /f
START regedit
to replace:
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Veritas\NetBackup\CurrentVersion\Config
with your registry path.
There's a program called RegJump, by Mark Russinovich, that does just what you want. It'll launch regedit and move it to the key you want from the command line.
RegJump uses (or at least used to) use the same regedit window on each invoke, so if you want multiple regedit sessions open, you'll still have to do things the old fashioned way for all but the one RegJump has adopted. A minor caveat, but one to keep note of, anyway.
From http://windowsxp.mvps.org/jumpreg.htm (I have not tried any of these):
When you start Regedit, it automatically opens the last key that was viewed. (Registry Editor in Windows XP saves the last viewed registry key in a separate location). If you wish to jump to a particular registry key directly without navigating the paths manually, you may use any of these methods / tools.
Option 1
Using a VBScript: Copy these lines to a Notepad document as save as registry.vbs
'Launches Registry Editor with the chosen branch open automatically
'Author : Ramesh Srinivasan
'Website: http://windowsxp.mvps.org
Set WshShell = CreateObject("WScript.Shell")
Dim MyKey
MyKey = Inputbox("Type the Registry path")
MyKey = "My Computer\" & MyKey
WshShell.RegWrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit\Lastkey",MyKey,"REG_SZ"
WshShell.Run "regedit", 1,True
Set WshShell = Nothing
Double-click Registry.vbs and then type the full registry path which you want to open.
Example: HKEY_CLASSES_ROOT\.MP3
Limitation: The above method does not help if Regedit is already open.
Note: For Windows 7, you need to replace the line MyKey = "My Computer\" & MyKey with MyKey = "Computer\" & MyKey (remove the string My). For a German Windows XP the string "My Computer\" must be replaced by "Arbeitsplatz\".
Option 2
Regjump from Sysinternals.com
This little command-line applet takes a registry path and makes Regedit open to that path. It accepts root keys in standard (e.g. HKEY_LOCAL_MACHINE) and abbreviated form (e.g. HKLM).
Usage: regjump [path]
Example: C:\Regjump HKEY_CLASSES_ROOT\.mp3
Option 3
12Ghosts JumpReg from 12ghosts.com
Jump to registry keys from a tray icon! This is a surprisingly useful tool. You can manage and directly jump to frequently accessed registry keys. Unlimited list size, jump to keys and values, get current key with one click, jump to key in clipboard, jump to same in key in HKCU or HKLM. Manage and sort keys with comments in an easy-to-use tray icon menu. Create shortcuts for registry keys.
I'd also like to note that you can view and edit the registry from within PowerShell. Launch it, and use set-location to open the registry location of your choice. The short name of an HKEY is used like a drive letter in the file system (so to go to HKEY_LOCAL_MACHINE\Software, you'd say: set-location hklm:\Software).
More details about managing the registry in PowerShell can be found by typing get-help Registry at the PowerShell command prompt.
Here is one more batch file solution with several enhancements in comparison to the other batch solutions posted here.
It sets also string value LastKey updated by Regedit itself on every exit to show after start the same key as on last exit.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "RootName=Computer"
set "RegKey=%~1"
if defined RegKey goto PrepareKey
echo/
echo Please enter the path of the registry key to open.
echo/
set "RegKey="
set /P "RegKey=Key path: "
rem Exit batch file without starting Regedit if nothing entered by user.
if not defined RegKey goto EndBatch
:PrepareKey
rem Remove double quotes and square brackets from entered key path.
set "RegKey=%RegKey:"=%"
if not defined RegKey goto EndBatch
set "RegKey=%RegKey:[=%"
if not defined RegKey goto EndBatch
set "RegKey=%RegKey:]=%"
if not defined RegKey goto EndBatch
rem Replace hive name abbreviation by appropriate long name.
set "Abbreviation=%RegKey:~0,4%"
if /I "%Abbreviation%" == "HKCC" set "RegKey=HKEY_CURRENT_CONFIG%RegKey:~4%" & goto GetRootName
if /I "%Abbreviation%" == "HKCR" set "RegKey=HKEY_CLASSES_ROOT%RegKey:~4%" & goto GetRootName
if /I "%Abbreviation%" == "HKCU" set "RegKey=HKEY_CURRENT_USER%RegKey:~4%" & goto GetRootName
if /I "%Abbreviation%" == "HKLM" set "RegKey=HKEY_LOCAL_MACHINE%RegKey:~4%" & goto GetRootName
if /I "%RegKey:~0,3%" == "HKU" set "RegKey=HKEY_USERS%RegKey:~3%"
:GetRootName
rem Try to determine automatically name of registry root.
if not exist %SystemRoot%\Sysnative\reg.exe (set "RegEXE=%SystemRoot%\System32\reg.exe") else set "RegEXE=%SystemRoot%\Sysnative\reg.exe"
for /F "skip=2 tokens=1,2*" %%K in ('%RegEXE% QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit" /v "LastKey"') do if /I "%%K" == "LastKey" for /F "delims=\" %%N in ("%%M") do set "RootName=%%N"
rem Is Regedit already running?
%SystemRoot%\System32\tasklist.exe /NH /FI "IMAGENAME eq regedit.exe" | %SystemRoot%\System32\findstr.exe /B /I /L regedit.exe >nul || goto SetRegPath
echo/
echo Regedit is already running. Path can be set only when Regedit is not running.
echo/
set "UserChoice=N"
set /P "UserChoice=Terminate Regedit (y/N): "
if /I "%UserChoice:"=%" == "y" %SystemRoot%\System32\taskkill.exe /IM regedit.exe >nul 2>nul & goto SetRegPath
echo Switch to running instance of Regedit without setting entered path.
goto StartRegedit
:SetRegPath
rem Add this key as last key to registry for Regedit.
%RegEXE% ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit" /v "LastKey" /d "%RootName%\%RegKey%" /f >nul 2>nul
:StartRegedit
if not exist %SystemRoot%\Sysnative\cmd.exe (start %SystemRoot%\regedit.exe) else %SystemRoot%\Sysnative\cmd.exe /D /C start %SystemRoot%\regedit.exe
:EndBatch
endlocal
The enhancements are:
Registry path can be passed also as command line parameter to the batch script.
Registry path can be entered or pasted with or without surrounding double quotes.
Registry path can be entered or pasted or passed as parameter with or without surrounding square brackets.
Registry path can be entered or pasted or passed as parameter also with an abbreviated hive name (HKCC, HKCU, HKCR, HKLM, HKU).
Batch script checks for already running Regedit as registry key is not shown when starting Regedit while Regedit is already running. The batch user is asked if running instance should be terminated to restart it for showing entered registry path. If the batch user chooses not to terminate all instances of Regedit, Regedit is started without setting entered path resulting (usually) in just getting Regedit window to foreground.
The batch file tries to automatically get name of registry root which is on English Windows XP My Computer, on German Windows XP, Arbeitsplatz, and on Windows 7 and newer Windows just Computer. This could fail if the value LastKey of Regedit is missing or empty in registry. Please set the right root name in third line of the batch code for this case.
The batch file runs on 64-bit Windows always Regedit in 64-bit execution environment even on batch file being processed by 32-bit %SystemRoot%\SysWOW64\cmd.exe on 64-bit Windows which is important for registry keys affected by WOW64.
Copy the below text and save it as a batch file and run
#ECHO OFF
SET /P "showkey=Please enter the path of the registry key: "
REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit" /v "LastKey" /d "%showkey%" /f
start "" regedit
Input the path of the registry key you wish to open when the batch file prompts for it, and press Enter. Regedit opens to the key defined in that value.
I thought this C# solution might help:
By making use of an earlier suggestion, we can trick RegEdit into opening the key we want even though we can't pass the key as a parameter.
In this example, a menu option of "Registry Settings" opens RegEdit to the node for the program that called it.
Program's form:
private void registrySettingsToolStripMenuItem_Click(object sender, EventArgs e)
{
string path = string.Format(#"Computer\HKEY_CURRENT_USER\Software\{0}\{1}\",
Application.CompanyName, Application.ProductName);
MyCommonFunctions.Registry.OpenToKey(path);
}
MyCommonFunctions.Registry
/// <summary>Opens RegEdit to the provided key
/// <para><example>#"Computer\HKEY_CURRENT_USER\Software\MyCompanyName\MyProgramName\"</example></para>
/// </summary>
/// <param name="FullKeyPath"></param>
public static void OpenToKey(string FullKeyPath)
{
RegistryKey rKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Applets\Regedit", true);
rKey.SetValue("LastKey",FullKeyPath);
Process.Start("regedit.exe");
}
Of course, you could put it all in one method of the form, but I like reusablity.
Here is a simple PowerShell function based off of this answer above https://stackoverflow.com/a/12516008/1179573
function jumpReg ($registryPath)
{
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit" `
-Name "LastKey" `
-Value $registryPath `
-PropertyType String `
-Force
regedit
}
jumpReg ("Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run") | Out-Null
The answer above doesn't actually explain very well what it does. When you close RegEdit, it saves your last known position in HKCU:\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit, so this merely replaces the last known position with where you want to jump, then opens it.
Create a BAT file using clipboard.exe and regjump.exe
to jump to the key in the clipboard:
clipboard.exe > "%~dp0clipdata.txt"
set /p clipdata=input < "%~dp0clipdata.txt"
regjump.exe %clipdata%
( %~dp0 means "the path to the BAT file" )
Building on lionkingrafiki's answer, here's a more robust solution that will accept a reg key path as an argument and will automatically translate HKLM to HKEY_LOCAL_MACHINE or similar as needed. If no argument, the script checks the clipboard using the htmlfile COM object invoked by a JScript hybrid chimera. The copied data will be split and tokenized, so it doesn't matter if it's not trimmed or even among an entire paragraph of copied dirt. And finally, the key's existence is verified before LastKey is modified. Key paths containing spaces must be within double quotes.
#if (#CodeSection == #Batch) #then
:: regjump.bat
#echo off & setlocal & goto main
:usage
echo Usage:
echo * %~nx0 regkey
echo * %~nx0 with no args will search the clipboard for a reg key
goto :EOF
:main
rem // ensure variables are unset
for %%I in (hive query regpath) do set "%%I="
rem // if argument, try navigating to argument. Else find key in clipboard.
if not "%~1"=="" (set "query=%~1") else (
for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0"') do (
set "query=%%~I"
)
)
if not defined query (
echo No registry key was found in the clipboard.
goto usage
)
rem // convert HKLM to HKEY_LOCAL_MACHINE, etc. while checking key exists
for /f "delims=\" %%I in ('reg query "%query%" 2^>NUL') do (
set "hive=%%~I" & goto next
)
:next
if not defined hive (
echo %query% not found in the registry
goto usage
)
rem // normalize query, expanding HKLM, HKCU, etc.
for /f "tokens=1* delims=\" %%I in ("%query%") do set "regpath=%hive%\%%~J"
if "%regpath:~-1%"=="\" set "regpath=%regpath:~0,-1%"
rem // https://stackoverflow.com/a/22697203/1683264
>NUL 2>NUL (
REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit"^
/v "LastKey" /d "%regpath%" /f
)
echo %regpath%
start "" regedit
goto :EOF
#end // begin JScript hybrid chimera
// https://stackoverflow.com/a/15747067/1683264
var clip = WSH.CreateObject('htmlfile').parentWindow.clipboardData.getData('text');
clip.replace(/"[^"]+"|\S+/g, function($0) {
if (/^\"?(HK[CLU]|HKEY_)/i.test($0)) {
WSH.Echo($0);
WSH.Quit(0);
}
});
This seems horribly out of date, but Registration Info Editor (REGEDIT) Command-Line Switches claims that it doesn't support this.
You can make it appear like regedit does this behaviour by creating a batch file (from the submissions already given) but call it regedit.bat and put it in the C:\WINDOWS\system32 folder. (you may want it to skip editting the lastkey in the registry if no command line args are given, so "regedit" on its own works as regedit always did) Then "regedit HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0" will do what you want.
This uses the fact that the order in PATH is usually C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem; etc
If the main goal is just to avoid "the clicking", then in Windows 10 you can just type or paste the destination path into RegEdit's address bar and hit enter.
The Computer\ prefix here is added automatically. It will also work if you simply type or paste a path starting with e.g. HKEY_CURRENT_USER\....
PowerShell code:
# key you want to open
$regKey = "Computer\HKEY_LOCAL_MACHINE\Software\Microsoft\IntuneManagementExtension\Policies\"
# set starting location for regedit
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit" "LastKey" $regKey
# open regedit (-m allows multiple regedit windows)
regedit.exe -m
This is the best answer overall, as it's quick, simple and there's no need to install any program.
By Byron Persino, improved by Matt Miller. (Many thanks to both of them!)
I'm rewording more correctly and clearly to help other readers like me, as I had a lot of trouble getting it clear and make it working.
Make a .bat file, eg. 'GoToRegEditPath.bat' , write the following code inside and save it:
CODE:
#echo off
set /p regPath="Open regedit at path: "
REG ADD HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit /v LastKey /t REG_SZ /d "%regPath%" /f
START regedit
exit
:: source:
https://stackoverflow.com/questions/137182/how-to-launch-windows-regedit-with-certain-path?answertab=modifieddesc#tab-top
Maybe this .bat use must "Run as Administrator"
To use it, Just run it and paste (R-Click) in it the copied RegEdit Path.
Tip: if R-click does not work inside command prompt:
R-click on title bar > Properties > check both under "Edit Options"