I need to be able to, if possible, via a batch file to export a user's mapped drive.
What I was thinking was have it load their ntuser.dat file, export hkey_current_user\Network key and save it to a certain location.
Is that possible?
Here's the script to call their username, this will be done locally on the computer:
:: Call the User Name :::::
:start
echo.
SET /P EndUserUN=EndUserUN:
echo.
REGEDIT.EXE /L:C:\Users\%EndUserUN%\NTUSER.DAT
Here's an example of a registry based script which should be Run as administrator and may perform the task for all of your users except for whoever you've logged in as:
#Echo Off
Set "EK=Network"
Set "RK=HKLM"
Set "SK=SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
Set "UI=S-1-5-21-"
Set "RV=ProfileImagePath"
Set "UH=NTUSER.DAT"
Set "TK=TmpHive"
Set "ER=HKU"
For /F "EOL=H Tokens=2*" %%A In (
'"Reg Query "%RK%\%SK%" /K /F "%UI%*" /S /V "%RV%" 2>Nul|FindStr /V "\.$""'
) Do (Reg Load "%ER%\%TK%" "%%~B\%UH%" 2>Nul
Reg Export "%ER%\%TK%\%EK%" "%~dp0%%~nxB.reg" /Y 2>Nul
Reg UnLoad "%ER%\%TK%" 2>Nul)
It is absolutely untested!
NoteDo not modify any line other than line 2, (which is currently Set to the SubKey path you are hoping to save as a .reg file).
Related
i want to export HKEY_LOCAL_MACHINE\SOFTWARE\ABC\EFGH string XYZ value 12. i looked into regedit /e and Reg export. it gives options to export till HKEY_LOCAL_MACHINE\SOFTWARE\ABC\EFGH, but not my string value XYZ.
I can think of no native method of exporting just a particular value with its data directly as a .reg file.
The best advice would be that you parse the output from reg query for your particular value data, and save it as a reg add command to another batch file. Then when, or if, you need to replace that value data with the previously saved data, you can just run that saved batch file.
Below is a basic example, (designed only for use with value type REG_SZ). I've used a common registry subkey and value for demonstration purposes, (because yours was not clear to me); please replace those on lines 4 and 5 as per your specific requirements:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "RegistryKey=HKEY_CURRENT_USER\Control Panel\Desktop"
Set "ValueName=Wallpaper"
Set "ValueData="
For /F "Tokens=*" %%G In ('%SystemRoot%\System32\reg.exe Query "%RegistryKey%"
/V "%ValueName%" 2^>NUL ^| %SystemRoot%\System32\findstr.exe /R "\<REG_SZ\>"'
) Do (Set "ValLine=%%G" & SetLocal EnableDelayedExpansion
For /F "UseBackQ Tokens=1,*" %%H In ('!ValLine:*%ValueName%^=!'
) Do EndLocal & Set "ValueData=%%I")
If Defined ValueData Echo #%%SystemRoot%%\System32\reg.exe Add "%RegistryKey%"^
/V "%ValueName%" /T REG_SZ /D "%ValueData:"=\"%" /F 1^>NUL 1>"%ValueName%.cmd"
If the string value is successfully found, its data will be saved to a local variable %ValueData%, for further use within the script if required. In addition, a batch file with the name of the registry value, should be output to the current directory. If you wish to change that name or location, please replace %ValueName%.cmd on the last line as needed. To restore the data at a later time just run the saved batch file.
I have written a batch file that I use for file management. The batch file parses an .XML database to get a list of base filenames, then allows the user to move/copy those specific files into a new directory. The program prompts the user for a source directory and the name of the .XML file. I would like the program to default the variables to the last used entry, even if the previous CMD session has closed. My solution has been to ask the user for each variable at the beginning of the program, then write those variables to a separate batch file called param.bat at the end like this:
#echo off
set SOURCEDIR=NOT SET
set XMLFILE=NOT SET
if exist param.bat call param.bat
set /p SOURCEDIR=The current source directory is %SOURCEDIR%. Please input new directory or press [Enter] for no change.
set /p XMLFILE=The current XML database is %XMLFILE%. Please input new database or press [Enter] for no change.
REM {Rest of program goes here}
echo #echo off>param.bat
echo set SOURCEDIR=%SOURCEDIR%>>param.bat
echo set XMLFILE=%XMLFILE%>>param.bat
:END
I was hoping for a more elegant solution that does not require a separate batch file and allows me to store the variable data within the primary batch file itself. Any thoughts?
#echo off
setlocal
dir /r "%~f0" | findstr /c:" %~nx0:settings" 2>nul >nul && (
for /f "usebackq delims=" %%A in ("%~f0:settings") do set %%A
)
if defined SOURCEDIR echo The current source directory is %SOURCEDIR%.
set /p "SOURCEDIR= Please input new directory or press [Enter] for no change. "
if defined XMLFILE echo The current XML database is %XMLFILE%.
set /p "XMLFILE=Please input new database or press [Enter] for no change. "
(
echo SOURCEDIR=%SOURCEDIR%
echo XMLFILE=%XMLFILE%
) > "%~f0:settings"
This uses the Alternate Data Stream (ADS) of the batchfile to
save the settings.
NTFS file system is required. The ADS stream is lost if the
batchfile is copied to a file system other than NTFS.
The dir piped to findstr is to determine if the
stream does exist before trying to read from it.
This helps to avoid an error message from the for
loop if the ADS does not exist.
The for loop sets the variable names and values read from the ADS.
Finally, the variables are saved to the ADS.
Note:
%~f0 is full path to the batchfile.
See for /? about all modifiers available.
%~f0:settings is the batchfile with ADS named settings.
dir /r displays files and those with ADS.
Important:
Any idea involving writing to the batchfile could result
in file corruption so would certainly advise a backup of
the batchfile.
There is one way to save variables itself on the bat file, but, you need replace :END to :EOF
:EOF have a good explained in this link .:|:. see Where does GOTO :EOF return to?
Also, this work in fat32/ntfs file system!
You can write the variables in your bat file, and read when needs:
Obs.: Sorry my limited English
#echo off & setlocal enabledelayedexpansion
set "bat_file="%temp%\new_bat_with_new_var.tmp"" & type nul >!bat_file! & set "nop=ot Se"
for /f %%a in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo 0x40"') do set "delim=%%a"
type "%~f0"| findstr "!delim!"| find /v /i "echo" >nul || for %%s in (SOURCEDIR XMLFILE) do set "%%s=N!nop!t"
if defined SOURCEDIR echo/!SOURCEDIR!%delim%!XMLFILE!%delim%>>"%~f0"
for /f "delims=%delim% tokens=1,2" %%a in ('type "%~f0"^| findstr /l "!delim!"^| find /v /i "echo"') do (
set /p "SOURCEDIR=The current source directory is %%~a. Please input new directory or press [Enter] for no change: "
set /p "XMLFILE=The current XML database is %%~b. Please input new database or press [Enter] for no change: "
if /i "!old_string!" neq "!SOURCEDIR!!delim!!XMLFILE!!delim!" (
type "%~f0"| findstr /vic:"%%~a!delim!%%~b!delim!">>!bat_file!"
copy /y !bat_file! "%~f0" >nul
echo/!SOURCEDIR!!delim!!XMLFILE!!delim!>>%~f0"
goto :_continue_:
))
:_continue_:
rem :| Rest of program goes here | replace/change last command [goto :END] to [goto :EOF]
goto :EOF
rem :| Left 2 line blank above, because your variable will be save/read in next line above here |:
Currently looking for a way to delete all icons off of all user desktops. I have experimented until I made the following script that allowed me to delete all from a single user but without hard coding I won't be able to extend this to reach all users on a single PC.
#echo off
cd %%#
del C:\Users\%Userprofile%\Desktop\*.* /s /q
for /r %%# in (.) do rmdir %%# /s
cls
I am now looking to see if it is possible to extend this to multiple users without hard coding paths since I don't happen to know which user might be using the computer at the time.
Since you don't want to hard code path's, we can use the FOR to search for .ico files located in \Desktop for each user. The script bellow will search each users desktop, remove all .ico files, then prompt the user it has finished.
#ECHO OFF
#GOTO :search
:search
FOR /D %%G IN ("C:\Users\*") DO IF EXIST "%%~fG\desktop\*.ico" (
set correctDir=%%G\desktop
goto :foundFile
)
goto :finished
:foundFile
cd "%correctDir%"
del /S *.ico
goto :search
:finished
echo All Icons removed from users desktops!
pause
goto :eof
FOR /D iterates over all directories using the %%G variable. %%~fG expands to the full path to the directory in %%G.
IF EXIST checks if a file exists.
goto :eof exits the script
Extreme care must be taken when writing or working with scripts which are intended to delete files/folders. A single minor mistake can end up in a disaster.
For example this code: cd "MyFolder" & del /q *.* is extremely dangerous it delete all files from current directory with the assumption that previous cd command have changed the current directory to MyFolder, So in case of failure del command will delete all files from current directory which is not MyFolder. But this code is safe: cd "MyFolder" && del /q *.*. The del command will be executed only if the cd command have successfully changed the current directory to MyFolder.
Now back to your original problem of extending your code to wipe out 'Desktops' of all other users of the PC.
The first thing that should be considered is that a normal user typically does not have access to desktop folders of other users because of NTFS file system permissions which avoids non Administrators from accessing other users profile. So the resulting script will have to run with administrative privileges. Even running the script as Administrator does guarantee the success because each user can explicitly deny access to his/her user profile files/folders even to Administrators.
The other thing is while it is mostly the case that the desktop directory of each user is placed in a folder named Desktop located in the %USERPROFILE% directory e.g. C:\Users\John\Desktop but this is not always the case. In fact the desktop directory of each user can defined to be located anywhere and placed in a folder other than Desktop.
This is the case for other special folders other than Desktop.
So the correct approach is to first retrieve a list of user profiles from registry and then for each user profile query the location of user's desktop.
:: WipeDesktops.cmd
:: This script should be runned as Administrator to be able to access and delete the 'Desktop' contents of other users.
#echo off
setlocal EnableExtensions EnableDelayedExpansion
:: To turn TestMode off It is highly recommended that to invoke the script with "/TestMode:Off" switch rather than manually setting TestMode to 0
set "TestMode=1"
set "DeleteCommandConfirm=rd /s"
set "DeleteCommandUnsafe=rd /s /q"
for /F "tokens=1,2 delims=:" %%A in ("%~1") do if /i "%%A"=="/TestMode" (
if /i "%%B"=="Off" (set "TestMode=0") else set "TestMode=1"
)
set "DeleteCommand=%DeleteCommandConfirm%"
if %TestMode% NEQ 0 (
echo Running in Test Mode
set "DeleteCommand=echo %DeleteCommand%"
) else (
set "DeleteCommand=2>nul %DeleteCommand%"
)
set "SID_Prefix=S-1-5-21-"
set "ProfileList=HKLM\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
set "ShellFoldersBase=Software\Microsoft\Windows\CurrentVersion\Explorer"
set "ShellFolders=%ShellFoldersBase%\Shell Folders"
set "UserShellFolders=%ShellFoldersBase%\User Shell Folders"
for /F "delims=" %%K in ('reg query "%ProfileList%" /k /f "%SID_Prefix%"') do (
set "ProfileKey=%%~K"
set "ProfileKey=!ProfileKey:HKEY_LOCAL_MACHINE\=HKLM\!"
if "!ProfileKey!" NEQ "!ProfileKey:HKLM\=!" (
set "ProfilePath="
for /F "tokens=2*" %%A in ('reg query "!ProfileKey!" /v "ProfileImagePath" 2^>nul') do (
set "ProfilePath=%%~B"
)
if defined ProfilePath if exist "!ProfilePath!\" (
set "Desktop="
set "SID=!ProfileKey:%ProfileList%\=!"
for %%S in ("%UserShellFolders%", "%ShellFolders%") do (
if not defined Desktop (
for /F "tokens=2*" %%A in ('reg query "HKU\!SID!\%%~S" /v "Desktop" 2^>nul') do (
set "Desktop=%%~B"
)
if defined Desktop (
REM %USERPROFILE% value is different for each user so it can not be expanded
for %%A in ("!ProfilePath!") do set "Desktop=!Desktop:%%USERPROFILE%%=%%~A!"
if not exist "!Desktop!\" set "Desktop="
)
)
)
if not defined Desktop set "Desktop=!ProfilePath!\Desktop"
REM Skip network paths
if "!Desktop:~0,2!" NEQ "\\" if exist "!Desktop!\" (
cd /d "!Desktop!" 2>nul && (
echo Removing 'Desktop' contents in !Desktop! ...
REM Since there is an open handle to the 'Desktop' folder, The contents of the folder will be removed but the folder itself remains.
%DeleteCommand% "!Desktop!"
)
)
)
)
)
For safety reasons it has 2 modes of operation:
Test Mode (the default): In this mode it only shows the commands along with the path that it can delete but no actual deletion will be performed
Normal Mode (invoke with /TestMode:Off switch) which will list and actually deletes the detected user desktops.
How it works
It first retrieves a list user profiles from registry key: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList each of them located under a registry key with a name that is equal to the corresponding user SID beginning with S-1-5-21-
for each SID key it queries the value of ProfileImagePath to obtain the location of the user profile directory.
Then it queries the location of user's desktop from two registry locations in the listed order:
HKEY_USERS\<SID>\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
HKEY_USERS\<SID>\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
and uses the value of ProfileImagePath to resolve the value of %USERPROFILE% variable for that user which is typically present in the special locations under the User Shell Folders key
Finally if the location of user's desktop can not be determined through registry then the default path of %USEPROFILE%\Desktop is assumed.
What is missing?
Shared user desktop is not covered, which is commonly located at %ALLUSERSPROFILE%\Desktop or %PUBLIC%\Desktop depending on windows version.
But the definite location can be obtained from these registry keys:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
So I'll leave it to you to do the rest and complete the missing part.
I want to copy the particular logfile generated for each day in one of my server which i have access to my local daily automatically.
I prepared the batch commands as follows but didn't work as expected.
echo off
SET logfiles=\\PWWAS0015\UMS_Logs\server1\ums\service-*.log
rem set var = C:\Users\L068699\Desktop\test\src
echo %logfiles%
copy %logfiles% C:\Users\L068699\Desktop\test\
set yesterday = [DateTime]::Today.AddDays(-1).ToString("yyMMdd")
echo %yesterday%
pause
The problem is that I cana ble to extract all the logs but couldn't get the log which are like service-2015-04-17.log. How can I extract this kind of log which are one day behind i.e. if today is 2015-04-24 I should get the previous day log file service-2015-04-23.log
try like this:
pushd \\PWWAS0015\UMS_Logs\server1\ums\
rem set var = C:\Users\L068699\Desktop\test\src
::echo service-*.log
for /f "usebackq" %%a in (`"powershell (Get-Date).AddDays(-1).ToString('yyyy-MM-dd')"`) do set yesterday=%%a
echo %yesterday%
copy service-%yesterday%.log C:\Users\L068699\Desktop\test\
pause
Eventually you'll need NET command to map the network drivre:
NET USE \\PWWAS0015\UMS_Logs /PERSISTENT:YES
(put the net use before the pushd if it does not work)
Try this, may help you..
#echo
set source1="\\xxx"
set dest="\\yyy"
pushd %source1%
for /f "usebackq" %%i in (`"powershell (Get-Date).AddDays(-1).ToString('yyyy-MM-dd')"`) do set yesterday=%%~i
copy "yourfilename %yesterday%.log" "%dest%"
popd
I have a batch file which I am calling from C++ using system("name.bat"). In that batch file I am trying to read the value of a registry key. Calling the batch file from C++ causes set KEY_NAME=HKEY_LOCAL_MACHINE\stuff to fail.
However, when I directly run the batch file (double clicking it), it runs fine. Not sure what I am doing wrong.
Batch file:
set KEY_NAME=HKEY_LOCAL_MACHINE\SOFTWARE\Ansoft\Designer\2014.0\Desktop
set VALUE_NAME=InstallationDirectory
REG QUERY %KEY_NAME% /v %VALUE_NAME%
C++ file:
int main(void)
{
system("CALL C:\\HFSS\\setup_vars.bat");
return 0;
}
UPDATE 1:
I found out that the key is actually in the 64-bit registry, and I was building my C++ solution as a 32-bit. Once I fixed that, it found the registry key fine.
Now I am having an issue adding that path to my PATH variable. Instead of creating a system variable, it is creating a user variable PATH and adding it there.
Running from command line works.
Code:
set KEY_NAME=HKLM\SOFTWARE\Ansoft\Designer\2014.0\Desktop\
set VALUE_NAME=InstallationDirectory
FOR /F "usebackq skip=1 tokens=1,2*" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME%`) DO (
set ValueName=%%A
set ValueType=%%B
set ValueValue=%%C
)
if defined ValueName (
#echo Value Value = %ValueValue%
) else (
#echo %KEY_NAME%\%VALUE_NAME% not found.
)
:: Set PATH Variable
set path_str=%PATH%
set addPath=%ValueValue%;
echo %addPath%
echo %ValueValue%
echo %PATH%| find /i "%addPath%">NUL
if NOT ERRORLEVEL 1 (
SETX PATH "%PATH%
) else (
SETX PATH "%PATH%;%addPath%;" /M
)
UPDATE 2:
I moved the placement of the option /M and it is now adding to right PATH variable.
However, when I am doing this, it is adding the PATH more than once (3 times) and then it is also adding a path to visual studio amd64 folder.
I'm mot sure why that is happening.
Windows creates a copy of the entire environment table of the process starting a new process for the new process. Therefore on start of your C++ application, your application gets the environment table including PATH from parent process, Windows Explorer or in your case Visual Studio. And this PATH is copied for cmd.exe on start of the batch file.
Taking the entire process tree into account from Windows desktop to the batch file, there have been many copies made for PATH and some processes perhaps appended something to their local copy of PATH like Visual Studio has done, or have even removed paths from PATH.
What you do now with SETX PATH "%PATH% is appending the local copy of PATH modified already by the parent processes in process tree completely to system PATH without checking for duplicate paths.
Much better would be to throw away all code using local copy of PATH and instead read the value of system PATH, check if the path you want to add is not already in system PATH and if this is not the case, append the path you want to add to system PATH using setx.
And this should be done without expanding the environment variables in system PATH like %SystemRoot%\System32 to C:\Windows\System32.
UPDATE
Here is the batch code required for your task tested on Windows 7 x64 and Windows XP x86.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "KeyName=HKLM\SOFTWARE\Ansoft\Designer\2014.0\Desktop"
set "ValueName=InstallationDirectory"
for /F "skip=2 tokens=1,2*" %%N in ('%SystemRoot%\System32\reg.exe query "%KeyName%" /v "%ValueName%" 2^>nul') do (
if /I "%%N" == "%ValueName%" (
set "PathToAdd=%%P"
if defined PathToAdd goto GetSystemPath
)
)
echo Error: Could not find non-empty value "%ValueName%" under key
echo %KeyName%
echo/
endlocal
pause
goto :EOF
:GetSystemPath
for /F "skip=2 tokens=1,2*" %%N in ('%SystemRoot%\System32\reg.exe query "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" /v "Path" 2^>nul') do (
if /I "%%N" == "Path" (
set "SystemPath=%%P"
if defined SystemPath goto CheckPath
)
)
echo Error: System environment variable PATH not found with a non-empty value.
echo/
endlocal
pause
goto :EOF
:CheckPath
setlocal EnableDelayedExpansion
rem The folder path to add must contain \ (backslash) as directory
rem separator and not / (slash) and should not end with a backslash.
set "PathToAdd=%PathToAdd:/=\%"
if "%PathToAdd:~-1%" == "\" set "PathToAdd=%PathToAdd:~0,-1%"
set "Separator="
if not "!SystemPath:~-1!" == ";" set "Separator=;"
set "PathCheck=!SystemPath!%Separator%"
if "!PathCheck:%PathToAdd%;=!" == "!PathCheck!" (
set "PathToSet=!SystemPath!%Separator%!PathToAdd!"
set "UseSetx=1"
if not "!PathToSet:~1024,1!" == "" set "UseSetx="
if not exist %SystemRoot%\System32\setx.exe set "UseSetx="
if defined UseSetx (
%SystemRoot%\System32\setx.exe Path "!PathToSet!" /M >nul
) else (
set "ValueType=REG_EXPAND_SZ"
if "!PathToSet:%%=!" == "!PathToSet!" set "ValueType=REG_SZ"
%SystemRoot%\System32\reg.exe ADD "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" /f /v Path /t !ValueType! /d "!PathToSet!" >nul
)
)
endlocal
endlocal
The batch code above uses a simple case-insensitive string substitution and a case-sensitive string comparison to check if the folder path to append is present already in system PATH. This works only if it is well known how the folder path was added before and the user has not modified this folder path in PATH in the meantime. For a safer method of checking if PATH contains a folder path see the answer on How to check if directory exists in %PATH%? written by Dave Benham.
Note 1: Command setx is by default not available on Windows XP.
Note 2: Command setx truncates values longer than 1024 characters to 1024 characters.
For that reason the batch file uses command reg to replace system PATH in Windows registry if either setx is not available or new path value is too long for setx. The disadvantage on using reg is that WM_SETTINGCHANGE message is not sent to all top-level windows informing Windows Explorer running as Windows desktop and other applications about this change of system environment variable. So the user must restart Windows which is best done always on changing something on persistent stored Windows system environment variables.
The batch script was tested with PATH containing currently a folder path with an exclamation mark and with a folder path being enclosed in double quotes which is necessary only if the folder path contains a semicolon.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
endlocal /?
for /?
goto /?
if /?
pause /?
reg /? and reg add /? and reg query /?
set /?
setlocal /?
setx /?