How to ask for Admin with batch - batch-file

I want to make a batch file which enables the Seconds in the Taskbar (There where you see the time).
I know you can do that manually when you open registry editor and go to
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced
And create there a DWORD-Value (32-Bit) and name it ShowSecondsInSystemClock and set the value on 1 and then Restart the Computer.
But now I want to make this in a batch file and that the User gets asked to enter his Password (The Password of the Computer) to continue (to make sure it is really the owner of the Computer). Is there a way to do that?
I'm really new to batch and I have only done basic stuff until now, I'm collecting my first experiences with programming.

Refer to the comment above posted by #Compo:
You don't need admin rights to change this setting in registry
And you don't need to restart the computer, just restart the exploer process
#echo off
Title Show Or Hide Seconds In System Clock
Color 9E & Mode 80,10 & SetLocal EnableDelayedExpansion
Set "Key=HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
::--------------------------------------------------------------------------
:GetInfo
#REM Get Opened Folders with PowerShell code in a batch file
Set PSCommand="#((New-Object -com shell.application).Windows()).Document.Folder | ForEach { $_.Self.Path }"
REM Populate the array with existent and opened folders
SetLocal EnableDelayedExpansion
Set /a Count=0
for /f "delims=" %%a in ('Powershell -C %PSCommand%') do (
Set /a Count+=1
Set "Folder[!Count!]=%%a"
)
::===========================================================================
:menuLOOP
::===========================================================================
echo(
echo(
echo( ***************************** Menu ******************************
echo(
#for /f "tokens=2* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do (
echo( %%A %%B)
echo(
echo( *****************************************************************
echo( &Set /p Selection=Make a Selection or hit ENTER to quit: || Goto :EOF
echo( & Call:menu_[%Selection%]
GOTO:menuLOOP
::===========================================================================
::---------------------------------
:menu_[1] Show Seconds In SystemClock
reg Add "%Key%" /V ShowSecondsInSystemClock /T REG_DWORD /D 1 /F 1>NUL
Call:Restart_Explorer
#rem Restore all closed folders
#for /L %%i in (1,1,%Count%) do Start /MAX Explorer "!Folder[%%i]!"
Exit /B
::---------------------------------
:menu_[2] Hide Seconds In SystemClock
reg Add "%Key%" /V ShowSecondsInSystemClock /T REG_DWORD /D 0 /F 1>NUL
Call:Restart_Explorer
#rem Restore all closed folders
#for /L %%i in (1,1,%Count%) do Start /MAX Explorer "!Folder[%%i]!"
Exit /B
::---------------------------------
:Restart_Explorer
powershell -C "gps explorer | spps"
Exit /B
::---------------------------------
Remark about alias used in PowerShell command to restart the explorer process:
gps is the Alias for Get-Process
spps is the alias for Stop-Process

Related

List Directory and number of files with specific extension, build a specific menu

I am trying to create a menu with submenus which their names without extension come from the directory. However, I am unable to make a variable for choice as number. This code does not work anyhow. I would also want to display a number at the beginning of each file name in the menu; in fact, number of the files will also be one of the number that user selects as input. I could not overcome the problem.
#echo off
cd C:\Users\Murray\Documents\ConfigFiles\
for /f %%A in ('dir /a-d-s-h /b *conf ^| find /v /c ""') do set count=%%A
echo File count = %count%
for %%F in ("C:\Users\Murray\Documents\ConfigFiles\*.conf") do echo %%~nxF
set choice=
set /C /N="Please choice: "
if "%choice%" == "%count%" goto SUBMENU
if NOT EXIST "C:\Users\Murray\Documents\ConfigFiles\%choice%" goto NOFILE
:SUBMENU
Echo You are here
goto end
:NOFILE
echo %choice% could not be found.
goto END
:end
Any help will be appreciated.
Here's a quick example of a method touted in the answer by on no. It will print a number to the screen followed by the names of each file matching file extension, so will allow a large number of matching files, (although the end user may have to scroll a long list). Once a file is chosen, your end user then just types its corresponding number. The code should not proceed beyond the input request until a number matching one in the list is ENTERed.
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "src=C:\Users\Murray\Documents\ConfigFiles"
Set "ext=.config"
If Not Exist "%src%\*%ext%" Echo No file matches.& GoTo End
For /F "Delims==" %%G In ('"(Set #) 2>NUL"') Do Set "%%G="
For /F "Delims==" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe OS Call /? ^|
%SystemRoot%\System32\find.exe "=="') Do Set "HT=%%G"
For /F "Tokens=1* Delims=:" %%G In ('Dir /B /A:-D "%src%\*%ext%" 2^>NUL ^|
%SystemRoot%\System32\findstr.exe /E /I /L /N "%ext%"'
) Do Set "#%%G=%%H" & Echo( %%G.%HT:~-1%%%H
If Not Defined #1 Echo No file matches.& GoTo End
:Opt
Echo(
Set "HT=" & Set "opt="
Set /P "opt=Enter the number for your chosen file>"
If Not Defined opt (GoTo Opt) Else Set "opt=%opt:"=%"
Set # | %SystemRoot%\System32\findstr.exe /B /L "#%opt%=" 1>NUL || GoTo Opt
SetLocal EnableDelayedExpansion
For %%G In ("!#%opt%!") Do EndLocal & Set "opt=%%~G"
#Rem Your code goes below here
Echo(& Echo You Selected %opt%
#Rem Your code ends above here
:End
Setlocal EnableDelayedExpansion & For /F "Tokens=1,2" %%G In ("!CMDCMDLINE!"
) Do Endlocal & If /I "%%~nG" == "cmd" If /I "%%~H" == "/c" Echo(& Echo Press^
any key to exit.&Pause 1>NUL
All you need to do is to modify the variables values on lines 4 and 5, if necessary, in order to test it. I will not be supporting changes or additions beyond that. Once you have tested the code, you may insert your code between lines 25 and 29, replacing the example line I left there for your test.
Batch's limitations are to blame for sub-par corrections to this question.
Here's the best I could whip up in a few seconds:
#echo off
:one
cls
cd C:\Users\Murray\Documents\ConfigFiles\
for %%F in ("C:\Users\Murray\Documents\ConfigFiles\*.conf") do echo %%~nxF
echo.
echo Enter Configuration Name:
set/p "prompt=>"
if exist %prompt%.txt goto :two
if exist %prompt% goto :two
cls
echo File not found
pause >NUL
goto :one
:two
cls
REM When file is found, this code will run
pause >NUL
The set command does not prompt for user input unless specified with the /p switch. To make your code more friendly, i'd also recommend to prompt for the filepath earlier on in the code.
EDIT: A few alternative solutions: Declare the 9th option of the prompt of the choice command as a "second page" or "more" option. This would really be a pain for the user in a directory with tens or hundreds of files. Another; you can assign an integer to each file that matches your quasi-query and echo them before each filename on the screen, then allow the user to input the number to get that file. That seems fairly efficient, and if you'd like to explore one or both of those alternates I can help (if you need it).

batch to display folders to select from, user selects folder, then it copies that folder to another folder

So what I'm trying to do is, i have a bat file that makes timestamped backups(for example, 180126_053327 in the format: yymmdd_hhmmss). I'm trying to create this bat to add to it, so i can have it lookup those backups, display in console to allow the user to select the backup they want to restore by inputting the number they want and then copy it to a location.
so far what i have creates this:
Pic of what I have so far
The pic above is from the following script:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
set i=0
For /f %%a in ('dir I:\AM_Configs-backups\ /B /A /D') do (
set /a i+=1
echo !i! %%a
set dir!i!=%%a
)
echo.
set /p uin="Select a directory [1-!i!]: "
set udir=!dir%uin%!
echo Selected - %udir%
md c:\test2
copy %udir% c:\test2
#PAUSE
I keep getting this:
Select a directory [1-29]: 27
Selected - 180126_053327
The system cannot find the file specified.
Press any key to continue . . .
I got the script above from this link: Prompting user to select directory in batch file
It cannot be found because %udir% is not in the current directory. This means that your base directory, I:\AM_Configs-backups, needs to be pre-fixed to your Copy command.
Copy "I:\AM_Configs-backups\%udir%" "C:\test2"
Also here is an alternative to the linked example you provided in your question:
#Echo Off
SetLocal EnableDelayedExpansion
Set "baseDir=I:\AM_Configs-backups"
For /F "Delims==" %%A In ('"(Set dir[) 2>Nul"') Do Set "%%A="
Set "i=0"
For /D %%A In ("%baseDir%\*") Do (Set /A i+=1 & Set "dir[!i!]=%%~nxA")
If %i% Equ 1 (Set "dir[X]=%baseDir%\%dir[1]%") Else Call :Menu
Rem Your commands using the selected directory begin below
Echo you selected %dir[X]%
If Not Exist "C:\test2\" MD "C:\test2"
Copy "%dir[X]%" "C:\test2"
Pause
Exit /B
:Menu
For /L %%A In (1,1,%i%) Do (Echo %%A. !dir[%%A]!)
Set /P "dir[X]=Select a directory from the above list: "
If Not Defined dir[%dir[X]%] (ClS & GoTo Menu)
Set "dir[X]=%baseDir%\!dir[%dir[X]%]!"
You can adjust your base directory on line 3 and put your own commands from line 9 onwards, (up to the Exit /B).
You should consider using RoboCopy for copying directories!
Edit
For the XCopy version, you'd probably need to change to:
#Echo Off
SetLocal EnableDelayedExpansion
Set "baseDir=I:\AM_Configs-backups"
For /F "Delims==" %%A In ('"(Set dir[) 2>Nul"') Do Set "%%A="
Set "i=0"
For /D %%A In ("%baseDir%\*") Do (Set /A i+=1 & Set "dir[!i!]=%%~nxA")
If %i% Equ 1 (Set "dir[X]=%dir[1]%") Else Call :Menu
Rem Your commands using the selected directory begin below
Echo you selected %dir[X]%
XCopy "%baseDir%\%dir[X]%" "%AppData%\Awesomeminer\%dir[X]%" /S /I /F /Y 2>Nul
Echo Starting Awesome Miner...
Start "" "%ProgramFiles(x86)%\Awesome Miner\AwesomeMiner.exe"
Pause
Call "Switch-N-Bkup.bat"
Pause
Exit /B
:Menu
For /L %%A In (1,1,%i%) Do (Echo %%A. !dir[%%A]!)
Set /P "dir[X]=Select a directory from the above list: "
If Not Defined dir[%dir[X]%] (ClS & GoTo Menu)
Set "dir[X]=!dir[%dir[X]%]!"
For the RoboCopy version you'd change line 11 to:
RoboCopy "%baseDir%\%dir[X]%" "C:\test2\%dir[X]%" /S 2>Nul
...plus any additional switches you may need
I ended up using this cus i have another batch for switching and backing up:
to kinda give you an idea, i have a primary bat for switching and copying configs, which will start teh program automatically after their copied. in that bat i also have code for backing up current configs to a location using time/date and creates the folders in this format: yymmdd_hhmmss...i needed an easy restore function, which with the link and code you provided helped with the user able to select which folder to restore and copying it to the programs data folder to be used, then auto-starting the program using the copied config.
#Echo Off
SetLocal EnableDelayedExpansion
Set "baseDir=I:\AM_Configs-backups"
For /F "Delims==" %%A In ('"(Set dir[) 2>Nul"') Do Set "%%A="
Set "i=0"
For /D %%A In ("%baseDir%\*") Do (Set /A i+=1 & Set "dir[!i!]=%%~nxA")
If %i% Equ 1 (Set "dir[X]=%baseDir%\%dir[1]%") Else Call :Menu
Rem Your commands using the selected directory begin below
Echo you selected %dir[X]%
REM If Not Exist "C:\test2\" MD "C:\test2"
xcopy "%dir[X]%" "%USERPROFILE%\AppData\Roaming\Awesomeminer\" /S /F /R /Y
START C:\"Program Files (x86)"\"Awesome Miner"\AwesomeMiner.exe
ECHO Starting Awesome Miner...
#Pause
CALL Switch-N-Bkup.bat
exit /b
:Menu
For /L %%A In (1,1,%i%) Do (Echo %%A. !dir[%%A]!)
Set /P "dir[X]=Select a directory from the above list: "
If Not Defined dir[%dir[X]%] (ClS & GoTo Menu)
Set "dir[X]=%baseDir%\!dir[%dir[X]%]!"

Reg Query wiping computer when using remotely

Recently I got a script to query the reg set a value and then delete folders under the folder I puled from the query. Looks like this:
pause
FOR /F "TOKENS=2*" %%I IN ('REG QUERY "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\14.0\Outlook\Security" /V OutlookSecureTempFolder') Do SET "ValueData=%%J"
pause
echo Delete Outlook Temp. Files???
echo Enter to continue or Ctrl+C to cancel.
pause
del /q /f /s "%valuedata%\*.*"
del /q /f /s "%systemdrive%\Jacob'sTemp"
pause
echo --------------------------------------------------------------------------------
echo Complete! Goodbye!
echo --------------------------------------------------------------------------------
timeout /t 3
Works great when used locally. So I set up a robo copy to copy a folder with this script in it then use psexec to execute it remotely and it looks like this:
set /p cpu=
robocopy "\\nmcfs01\software\scripts\Jacob's Awesome Outlook Scripts" \\%cpu%\c$\Jacob'sTemp
pause
psexec \\%cpu% -u administrator "%systemdrive%\Jacob'sTemp\outlooktempdelete.bat"
pause
Now it works and it will run but here is the kicker when it goes back to the reg query batch to do the reg query it will run but it skips the 1st pause following the query and it always says it can not find the registry key but I can follow the path and it is there. The worst part is once I end the script there it wipes the computer of everything the user has access to. Not folders but all files/subfiles everywhere. Any insight is greatly appricated!
Here's a quick tidy up of your script:
#Echo Off
SetLocal EnableExtensions
(Set OV=14.0)
Choice /C YN /M "Delete Outlook Temp Files?"
If ErrorLevel 2 Exit/B
Set "BK=HKCU\SOFTWARE\Microsoft\Office\"
Set "EK=\Outlook\Security"
Set "VN=OutlookSecureTempFolder"
For /F "Tokens=2*" %%I In ('Reg Query "%BK%%OV%%EK%" /V %VN%') Do Set "VD=%%J"
PushD "%VD%" && (RD/S/Q "%VD%" 2>Nul) && PopD
REM The below commands will empty Jacob'sTemp:
If Exist "%SystemDrive%\Jacob'sTemp" (PushD "%SystemDrive%\Jacob'sTemp" && (
(RD/S/Q "%SystemDrive%\Jacob'sTemp" 2>Nul) && PopD
REM The below commands without the first two characters will remove Jacob'sTemp
::If Exist "%SystemDrive%\Jacob'sTemp" (RD/S/Q "%SystemDrive%\Jacob'sTemp"
Pause
Echo(------------------------------------------------------------------------------
Echo( Complete! Goodbye!
Echo(------------------------------------------------------------------------------
Timeout 5 >Nul
Give that a try exactly as it is just to see if it makes any difference.
I left the lonely but editable 'set' at the top because this is the only bit that need's changing to cater for earlier or later editions of outlook.

Create msgbox when running batch

#echo off
wmic csproduct get uuid
pause
wmic DISKDRIVE get SerialNumber
pause
getmac
pause
I need each one to pop its own message box, so when I click OK it moves to the next one and then the next one. At the end it saves all as a text document on the desktop. Currently being used in a .bat but if .vbs would be easier or better please tell me what code to use.
I have tried including msgbox, but not sure how to set the different codes with each box. I have tried to reverse engineer: Set WshShell = CreateObject("WScript.Shell") MsgBox ConvertToKey(WshShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DigitalProductId") But no such luck
Try like this way :
#echo off
Set Title="Example of MsgBox by Hackoo"
Set TmpFile=Tmp.txt
Set LogFile=%UserProfile%\Desktop\result.txt
(
for /f "delims=" %%G in ('wmic csproduct get uuid') do (echo "%%G" & Call:MsgBox "%%G" ,vbInformation,%Title%)
for /f "delims=" %%G in ('wmic diskdrive get SerialNumber') do (echo "%%G" & Call:MsgBox "%%G" ,vbInformation,%Title%)
for /f "delims=" %%G in ('getmac') do (echo %%G & Call:MsgBox "%%G" ,vbInformation,%Title%)
)>%TmpFile%
Cmd /U /C Type %TmpFile% > %LogFile%
Start "" %LogFile%
Del %TmpFile%
Exit /b
:MsgBox <Message> <Buttons Type> <Title>
Rem This function create a vbscript file %tmp%\Msg.vbs with 3 arguments and executes it
Rem First argument is %1 ==> To show the message
Rem Second argument is %2 ==> To choose the type of buttons
Rem Third argument is %3 ==> To show the Title
Rem Example how we can call this function :
Rem Call :MsgBox "This an example from Hackoo to say Hello to ""stackoverflow.com"" ",vbInformation,%Title%
Rem Call :MsgBox "This an example from Hackoo to show any kind of a Warning Message",vbExclamation,%Title%
Rem Call :MsgBox "This an example from Hackoo to show any kind of error",vbCritical,%Title%
(
echo MsgBox %1,%2,%3
)>%tmp%\Msg.vbs
cscript /nologo %tmp%\Msg.vbs
Del %tmp%\Msg.vbs

Batch script that makes a numbered menu to view log files

I have recently started to learn how to make batch files. I have a folder that contains bunch of internet related log files. When I run the .cmd file (located in the same folder) I want it to be able to find out how many log files are in the folder and make a numbered menu from it. So lets say there are twenty files in the folder, then the user must be able to select from 1 to 21. 21 will close the batch file. Here is what I have done so far:
#echo off
setlocal enableextensions enabledelayedexpansion
set RawData1=TempData%random%.tmp
set FileCtr=0
:MAIN
dir *.log /b | findstr /i /n ".log" > %RawData1%
for /f "tokens=1 delims=:" %%a in (%RawData1%) do set FileCtr=%%a
set /a ExitCode=%FileCtr% + 1
set UserChoice=%ExitCode%
echo.
echo +++++++++++++++++++++++++++
echo Weblog File Viewer
echo +++++++++++++++++++++++++++
for /f "tokens=1-2 delims=:." %%a in (%RawData1%) do echo %%a. %%b
echo %Exitcode%. To Quit.
set /p UserChoice= Choose item number from menu (%UserChoice%):
echo\
echo user entered: %UserChoice%
pause
:THEEND
del /q %RawData1%
So what this batch file can do for now is that it figures out the number of log files and makes a numbered menu from it. Of course it won't show the filetype which is how I wanted it. So "Kelley-Blue-Book.log" for example is shown only as "Kelley-Blue-Book". However, if the user selects say number 4 from the list the program will terminate because I couldn't figure out how to make it actually open the desired log file using notepad.
This should do what you want:
#echo Off
setlocal EnableDelayedExpansion
set "Count=0"
pushd "%~dp0"
echo.
echo +++++++++++++++++++++++++++
echo Weblog File Viewer
echo +++++++++++++++++++++++++++
for %%A in (*.log) do (
set /a "Count+=1"
set "Menu[!Count!]=%%~fA"
set "Number= !Count!"
echo !Number:~-3!. %%~nA
)
set /a "Count+=1"
set "Number= %Count%"
echo %Number:~-3%. To Quit.
:Prompt
set "UserChoice="
set /p "UserChoice= Choose item number from menu (%Count%):"
if not defined UserChoice goto Prompt
set "UserChoice=%UserChoice:"=%"
if "%UserChoice%"=="%Count%" goto Done
for /f "tokens=1,* delims==" %%A in ('set Menu') do (
if /i "Menu[%UserChoice%]"=="%%~A" (
notepad "%%~fB"
set "UserChoice="
)
)
if defined UserChoice echo Invalid Choice.
goto Prompt
:Done
popd
endlocal
exit /b 0
Let me know if you want any explanations.
#echo off
setlocal enableextensions
set RawData1=TempData%random%.tmp
rem Get numbered list of files
dir /b "*.log" | findstr /i /n ".log" > %RawData1%
rem We could use 0 as exitCode,
rem but to keep original behaviour
rem lets count the number of files
for /F "tokens=*" %%f in ('type %RawData1% ^| find /c /v "" ') do set /A ExitCode=%%f + 1
if %ExitCode%==0 (
echo No log files
goto endProcess
)
rem show menu
for /f "tokens=1-2 delims=:." %%a in (%RawData1%) do echo %%a. %%b
echo %Exitcode%. To Quit.
set UserChoice=%ExitCode%
set /p UserChoice= Choose item number from menu (%UserChoice%):
if "%UserChoice%"=="" goto :EOF
if "%UserChoice%"=="%ExitCode%" goto endProcess
rem Search indicated file in list
set SelectedFile=
for /f "tokens=2 delims=:" %%f in ('findstr /B "%UserChoice%:" %RawData1%') do set SelectedFile=%%f
if "%SelectedFile%"=="" (
echo Incorrect selection
goto endProcess
)
if not exist %SelectedFile% (
echo File deleted
goto endProcess
)
notepad %SelectedFile%
:endProcess
del /q %RawData1%

Resources