Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 11 months ago.
Improve this question
Is there any way we can add certificate using cmd/shell/bat silently without administrator rights in windows 10.
I have a command which silently add cert in "Trusted Publisher" :
certutil -addstore "TrustedPublisher" my_certificate.cer
But this command needs administrator command prompt to run.
According to comments below question, this batch should answer your needs:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
REM Check admin mode, auto-elevate if required.
openfiles > NUL 2>&1 || (
REM Not elevated. Do it.
echo createObject^("Shell.Application"^).shellExecute "%~dpnx0", "%*", "", "runas">"%TEMP%\%~n0.vbs"
cscript /nologo "%TEMP%\%~n0.vbs"
goto :eof
)
del /s /q "%TEMP%\%~n0.vbs" > NUL 2>&1
REM Can't be here without elevation.
certutil -addstore "TrustedPublisher" my_certificate.cer
goto :eof
The batch will ask for elevation automatically and then execute your command, in an elevated cmd, and terminate.
How it works:
openfiles is a standard program shipped with Windows 10 (for Windows 7, for example, I used to do that with fsutils instead).
This program have a particularity: it requires elevation, does nothing harmful with no parameter, and returns a suitable error code without elevation.
So, when you launch it without elevation, it prints an error message and returns 1.
With elevation, it prints things and returns 0.
Because we don't care about what it displays, both its stdout and stderr are sent to NUL.
So, when we're NOT elevated, the || operator will execute the code within parentheses. Otherwise, it skips it and go to the del line just after - this line is designed to clean the temporary file used for elevation, I'll explain it below.
So, we're not elevated. The purpose is to create a very tiny VBS script, within %TEMP% folder. In order to not mess with multiple batchs launched simultaneously, we name this temporary file following the current batch filename (that's the "%TEMP%%~n0.vbs" part).
The VBS contains a single command: it will call "ShellExecute" on the batch file itself (NOT the VBS), with all seen parameters (they're expanded when creating the VBS file, they're not passed to VBS then to BAT again) using the runas keyword - and here is the magic.
This keyword does this (see Microsoft documentation):
runas Launches an application as Administrator. User Account Control (UAC) will prompt the user for consent to run the application elevated or enter the credentials of an administrator account used to run the application.
Unfortunately, we can't call this function directly from a batch (at least not without some ugly tricks), but it's very easy and understandable to do so from a VBS. And VBS is standard on Windows, too.
So, we now launch the VBS, and we terminate the non-elevated batch with goto :eof. The VBS starts, and relaunch the batch, but with elevation (and an UAC prompt). The batch starts again, has all its previous command line parameters, will detect that it's already elevated.
We just need now to clean the temporary VBS file with the del command, and we can continue our batch being sure that we are in an elevated process.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
How do I modify the following batch script to kill a process instead of a task?
For example, if BBB.exe once executed runs as a process, how would I kill that process once AAA.exe is closed?
To clarify, if you open task manager, tasks are listed under the "applications" tab and a process is listed under the "processes" tab. The program represented as "BBB.exe" that I'm trying to kill immediately once AAA.exe is closed only opens to the system tray and not the task bar and therefore is not present in the "applications" tab but only the "processes" tab when open. The following batch file does not have any effect on ending program "BBB.exe" even when the machine is ran with admin privileges. I've seen the "Process.Kill()" command but I'm not sure how to properly utilize it.
Thanks in advance.
#Echo off
CD "C:\Users\XXX\XXX\XXX"
start AAA.exe
CD "C:\XXX\XXX"
start BBB.exe
:TEST
Tasklist /FI "IMAGENAME eq AAA.exe" 2>NUL | Find /I /N AAA.exe>NUL
If "%ERRORLEVEL%"=="0" goto ACTIVE
:DEAD
Taskkill /F /IM BBB.exe
Exit
:ACTIVE
Timeout /T 1
Goto TEST
I found out what the problem is.
The issue lies in that the "taskkill" command was never being deployed because command prompt remained in the directory of BBB.exe where the "taskkill" executable doesn't exist.
Simply changing the directoy to either "system32" or "syswow64" (depending on the OS installation) after executing both programs and before running the "taskkill" command in the batch file solved the issue.
I have to execute the ewfmgr.exe which can be executed only when the Command window is opened as an Admin.
If I go to Start->type cmd.exe->Right click->Run as Administrator then the following Comand prompt windows appear. In this window, if I write ewfmgr.exe (which the EXE file that I have to execute), then the command is executed without any problem.
MY REQUIREMENT: My requirement is to execute the command through a script file (RunasAdmin.cmd file) and this script file will be executed through an NSIS Installer.
Since, the ewfmgr.exe can be executed only with Admin, so I have to escalate my script to get Admin rights. For this, I have the following script:
Script to Get Admin Right: "(RunasAdmin.cmd)"
::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
::::::::::::::::::::::::::::::::::::::::::::
#echo off
CLS
ECHO.
ECHO =============================
ECHO Running Admin shell
ECHO =============================
:init
setlocal DisableDelayedExpansion
set cmdInvoke=0
set winSysFolder=System32
set "batchPath=%~0"
for %%k in (%0) do set batchName=%%~nk
set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
setlocal EnableDelayedExpansion
:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )
:getPrivileges
if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
ECHO.
ECHO **************************************
ECHO Invoking UAC for Privilege Escalation
ECHO **************************************
ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
ECHO args = "ELEV " >> "%vbsGetPrivileges%"
ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
ECHO args = args ^& strArg ^& " " >> "%vbsGetPrivileges%"
ECHO Next >> "%vbsGetPrivileges%"
if '%cmdInvoke%'=='1' goto InvokeCmd
ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
goto ExecElevation
:InvokeCmd
ECHO args = "/c """ + "!batchPath!" + """ " + args >> "%vbsGetPrivileges%"
ECHO UAC.ShellExecute "%SystemRoot%\%winSysFolder%\cmd.exe", args, "", "runas", 1 >> "%vbsGetPrivileges%"
:ExecElevation
"%SystemRoot%\%winSysFolder%\WScript.exe" "%vbsGetPrivileges%" %*
exit /B
:gotPrivileges
setlocal & pushd .
cd /d %~dp0
if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul & shift /1)
::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
REM Run shell as admin (example) - put here code as you like
ewfmgr c: -enable
pause
cmd /k
PROBLEM: If I execute the script (RunasAdmin.cmd) just by double clicking on it, the script is executed and get the task done without any error. But if I execute the script (RunasAdmin.cmd) through my NSIS installer (EWFMGR_Run.exe) then, I get an error that ewfmgr is not recognised as an internal or external command
NSIS Installer Code: (EWFMGR_Run.exe)
OutFile "EWFMGR_Run.exe"
section
ExecWait "D:\Disk\RunasAdmin.cmd"
sectionEnd
The Command window opened by NSIS installer after running the script (RunasAdmin.cmd) is following:
Queston: Both the command windows are opened as Admin and are into the same working directory. But how come the window opened by NSIS installer is not able to find ewfmgr.exe?
UPDATE-1: Bascially the problem is in the CMD window opened by the NSIS installer. Even if I move to the path C:\Windows\System32 manually using cd /D C:\Windows\System32 and try to execute ewfmgr.exe (which is available in that path), CMD does not recognize it.
References: The script file to elevate to Admin has been taken from Matt's answer given here.
What must be at least taken into account on elevating a command script (batch file) to administrator level?
The current directory changes in any case to %SystemRoot%\System32.
The environment could change completely if the current user is not in administrator group and therefore the user has to use a different user account to run the batch file with elevated privileges of an administrator, for example the local administrator account must be used instead of current user account. This affects environment variables and permissions on network resources.
The script is started initially always in environment of parent process which is on 64-bit Windows the 32-bit environment instead of the 64-bit environment in case of parent process is a 32-bit application.
The script could be executed with one or more arguments enclosed in double quotes which should be passed right to the script on execution with elevated privileges.
How to handle those 4 points?
1. Current directory
Many command line scripts (batch files) are coded to work with current directory and assume that the current directory is the same directory as the batch file. That the current directory is the same directory in which the batch file is stored is true on double clicking on a batch file stored on a local drive or a network drive, except the execution of batch files from network drives is disabled by security settings.
But Windows sets %SystemRoot%\System32 as current directory on running a cmd script as scheduled task using system account.
And Windows sets %SystemRoot%\System32 as current directory on using RunAs to run a cmd script with elevated administrator privileges.
And Windows sets %SystemRoot% as current directory after printing into console window the message below on executing a batch file with a double click which is stored on a network share opened using UNC path.
'\server\share\directory'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
Using UNC paths as current directory could be enabled as described for example by an answer on How to run batch file from network share without "UNC path are not supported" message?
The best would be to write the entire script code to work independent on which directory is the current directory.
That means not using just the file name of a referenced file, but "Full path to\FileName.exe", i.e. the file name with file extension and with full path enclosed in double quotes.
In case of all files to run or referenced from within a cmd script are stored in an unknown folder, but are always in same folder as the cmd script, the simple method to get path for all files is using the command line:
set "SourceFolder=%~dp0"
%~dp0 expands to path of the batch file always ending with a backslash and never being enclosed in double quotes even if the folder path contains a space character or other command line syntax critical characters like an ampersand.
Then all files are referenced with using
"%SourceFolder%FileName.exe"
Note: There is no backslash (directory separator on Windows) as the environment variable SourceFolder holds the folder path already with a backslash at end.
Of course it is also possible to use cd /D "%~dp0" to set current directory to the directory of the cmd script, but this does not work for UNC paths.
But there is also the command pushd "%~dp0" working also with UNC paths if command extensions are enabled as by default.
For details on the commands CD and PUSHD run in a command prompt window cd /? and pushd /? and read the output help.
2. Environment variables
Windows creates a copy of the currently active environment table of current process whenever a new process is created.
But this is not the case when a batch file elevates itself to administrator level. Therefore it is not possible to define environment variables on initial run of a batch file, then elevate to administrator level, and access now the environment variables as defined before in initial environment. It could even happen that the batch file was initially executed in 32-bit environment on 64-bit Windows on initial execution, but runs in 64-bit environment after elevation to administrator level.
So everything which needs to be passed from initial execution to elevated execution must be parsed via command line arguments or via a file on a local drive fully accessible in all environments, i.e. for everyone.
3. 32-bit versus 64-bit environment
Sometimes a 32-bit installer is used for installing either a 32-bit or a 64-bit application depending on bit width of Windows because of running on all Windows. The batch file is processed by 32-bit cmd.exe in 32-bit environment on using a 32-bit installer even when executed on a 64-bit Windows.
At least the following three Microsoft articles should be studied carefully before reading further:
File System Redirector
WOW64 Implementation Details
Registry Keys Affected by WOW64
It is definitely no good idea to depend on value of environment variable PROCESSOR_ARCHITECTURE as its value is x86 when a 32-bit process is executed on 64-bit Windows in 32-bit environment.
It is also not good to query the architecture of the processor directly from Windows registry. It is not guaranteed that there is a 64-bit Windows running on a computer with a 64-bit CPU. It is not often done, but nevertheless possible to use 32-bit Windows on a computer with a 64-bit processor on main board.
The environment variable ProgramFiles(x86) is not defined by default on 32-bit Windows as it is on 64-bit Windows which can be used to determine if a command file script is running on 32-bit or 64-bit Windows.
And the file %SystemRoot%\Sysnative\cmd.exe exists only for 32-bit processes running in 32-bit environment on 64-bit Windows because of special alias Sysnative existing only for a 32-bit process in 32-bit environment on 64-bit Windows which can be used to determine in which environment the batch file is currently running.
4. Passing arguments
It is easy to elevate a batch file executed without any arguments to elevated administrator level.
It is also no problem to pass simple arguments which do not need to be enclosed in double quotes to batch file running elevated.
But passing one or more arguments containing at least one space character or one of these characters &()[]{}^=;!'+,`~<|> which require enclosing the argument string in double quotes is really not easy, especially on creating a Visual Basic script from within a batch file to elevate to administrator level.
It is a real nightmare to try to encode double quotes in batch file correct to be passed via the VB script to the same batch file executed with elevated privileges. Most solutions provided in World Wide Web simply don't support double quoted parameters. Matt's Elevate.cmd - Version 4 is no exception. Running a batch file using this code with "%ProgramFiles%\Installation Folder" as first argument results on initial execution in "C:\Program Files\Installation Folder" being the first and only argument and on elevated execution after removing argument ELEV in the three arguments C:\Program, Files\Installation and Folder.
5. Possible solution for this task
For this task a 32-bit NSIS installer is calling a command line script which must elevate itself to administrator level and should run on 64-bit Windows in 64-bit environment instead of 32-bit environment as on initial run.
I have once analyzed the batch and VB script code of Matt's Elevate.cmd - Version 4, have removed all useless code, have enhanced it to support also arguments enclosed in double quotes using a much easier method than other posted, and have commented the code completely so that others can also understand it for answering UNC paths as current directories in batch file where admin rights are requested.
The batch script posted there is written to work independent on what is the current directory for working also with batch file being executed from a network share using UNC path which of course works only if the network share is still accessible according to permission settings of the share after elevation to administrator level. I found out today after a comment by Richard on his answer on Open Command Window in Windows x64 mode that the web page SS64 - Run with elevated permissions contains nearly the same code as I developed without having ever read the code there.
The adapted batch file code below should work for this task. It expects the executable ewfmgr.exe in same directory as the cmd script or ewfmgr.exe is specified with full path as first argument on executing the script in case of being in a different directory.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
cls
rem Define as application to run by default the file ewfmgr.exe in folder
rem of the batch file which can be a folder on a local drive or on a
rem network drive or even a UNC path.
set "AppToRun=%~dp0ewfmgr.exe"
set "vbsGetPrivileges=%TEMP%\OEgetPriv_%~n0.vbs"
rem The console application NET with parameter FILE can be executed
rem successfully only if the account used for running this batch file
rem has local administrator privileges. See the Microsoft documentation
rem https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-xp/bb490702(v=technet.10)
rem for details about NET FILE.
rem The output written to handle STDOUT on successful execution is redirected
rem to device NUL to suppress it. The exit code of NET assigned to ERRORLEVEL
rem is in this case 0 indicating a successful execution.
rem But on a failed execution because of not having administrator
rem privileges NET outputs to handle STDERR the two error messages
rem "System error 5 has occurred." and "Access is denied." which
rem are redirected from handle STDERR to device NUL to suppress them.
rem And exit/return code of NET is 1 indicating a failed execution.
rem Read https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-xp/bb490982(v=technet.10))
rem for details about using command redirection operators.
%SystemRoot%\System32\net.exe FILE >nul 2>nul
if not errorlevel 1 goto RunMainCode
if "%~1" == "ELEV" (
rem This condition is just for safety. If the batch file was started
rem already a second time with ELEV as first parameter and execution
rem of NET FILE failed nevertheless because of missing permissions,
rem the batch file outputs an error message, waits for any key press
rem by the user to make sure that the user had the chance to read the
rem error message and then exits the batch file processing without
rem doing anything at all.
echo %~nx0 should run already with elevated privileges, but it isn't.
echo/
echo Press any key to exit %~nx0 without doing anything ...
pause >nul
goto :EOF
)
rem This batch file can be started without any parameter resulting in %* being
rem expanded to nothing which results in environment variable BatchArgs being
rem deleted if already existing or with ewfmgr.exe with full path as parameter
rem which must be enclosed in double quotes in case of path containing
rem one or more spaces.
rem As the batch file needs to be executed once again in a separate command
rem process running as local administrator for full access at least on local
rem machine it is necessary to prepare the parameters/arguments list. Each
rem double quote in the arguments list must be doubled to be correct escaped
rem in the VB script file.
rem This is necessary as otherwise running this batch file with
rem "Full path to\ewfmgr.exe"
rem as first parameter would result in execution of the batch file by the
rem Windows Scripting Host as Full path to\ewfmgr.exe without the double
rem quotes as arguments for the batch file and therefore the first parameter
rem is on elevated execution "Full" instead of "Full path to\ewfmgr.exe" as
rem it was initially.
rem Many "run as administrator" solutions which can be found in World Wide Web
rem don't handle parameter strings correct which are enclosed in double quotes
rem because the parameter string has one or more spaces or other critical
rem characters requiring enclosing the parameter string in double quotes.
set "BatchArgs=%*"
setlocal EnableDelayedExpansion
if defined BatchArgs set "BatchArgs= !BatchArgs:"=""!"
rem Everything output by the ECHO command lines within the next command block
rem is redirected into the VB script file created in the folder for temporary
rem files of current user with name of batch file in VB script file name. This
rem makes it possible that multiple batch files with different names can run
rem at the same time using same code for creating a VB script file to run the
rem batch file once again as administrator with elevated privileges.
rem For details on ShellExecute parameters see the Microsoft documentation
rem https://learn.microsoft.com/en-us/windows/win32/shell/shell-shellexecute
rem The tricky part is quoting the arguments list correct which should be
rem finally passed to cmd.exe executed from the VB script. The command process
rem running the batch file with elevated privileges of local administrator
rem should automatically close after execution of batch file finished which
rem is the reason for first argument /C.
rem The second argument is the command to execute by `cmd.exe` which is
rem the batch file name with complete path which must be enclosed in double
rem quotes for safety in case of batch file name or path contains one or more
rem spaces. But additionally the batch file itself must be started with at
rem least two more arguments.
rem The first argument for the batch file is ELEV which is used as indication
rem to detect if this batch file is already started a second time via the
rem VB script using local built-in administrator account.
rem The second argument for the batch file is the application to
rem run with full default path which is the batch file folder.
rem And last all parameters passed to this batch file on initial run should
rem be also passed to second execution of this batch file under the different
rem environment of local built-in administrator account.
rem This nesting of batch file arguments in command processor arguments written
rem into a VB script file which requires additionally escaping each double quote
rem within a string with one more double quote results in a strange syntax for
rem the line to write into the VB script file.
(
echo Set UAC = CreateObject^("Shell.Application"^)
echo UAC.ShellExecute "%SystemRoot%\System32\cmd.exe", "/C """"%~f0"" ELEV ""!AppToRun!""!BatchArgs!""", , "runas", 1
)>"%vbsGetPrivileges%"
endlocal
rem Now the created VB script file can be executed with Windows Script Host.
rem Then the VB script file can be deleted as no longer needed and processing
rem of this batch file under current user account ends resulting in returning
rem to command process which results in closing the console window if not
rem executed by cmd.exe started with option /K to keep the console window
rem opened like on opening a command prompt window and running this batch
rem file from within the command prompt window.
%SystemRoot%\System32\WScript.exe "%vbsGetPrivileges%"
del "%vbsGetPrivileges%"
endlocal
goto :EOF
rem Here starts the main code of the batch file which needs to be
rem executed with elevated privileges of a local administrator.
rem First is checked if the first parameter of the batch file is ELEV
rem which indicates that this batch file was started a second time
rem using administrator privileges or local administrator account.
:RunMainCode
if "%~1" == "ELEV" (
rem In this case the second argument is the application to run with
rem batch file folder passed from initial run to this second run of
rem the batch file. The current directory is now not anymore the initial
rem current directory, but %SystemRoot%\System32 as set by Windows on
rem starting a command process using RunAs and administrator account.
rem This must be taken into account on further batch file processing.
rem For this batch file it does not matter what is the current directory
rem as it is written to work with path of the application to run defined
rem on starting the batch file (initially). So there is no need to use
rem CD /D "%~dp0" or PUSHD "%~dp0" as many "run as administrator"
rem solutions use to change the current directory to directory of the
rem batch file. There is also no need for CD /D "%~2" or PUSHD "%~2"
rem here which of course could be also used.
rem The two additionally added arguments ELEV and the application to
rem run are removed from the arguments lists by using twice the
rem command SHIFT to restore the initial arguments list.
set "AppToRun=%~2"
shift /1
shift /1
)
if "%ProgramFiles(x86)%" == "" goto RunApp
if not exist %SystemRoot%\Sysnative\cmd.exe goto RunApp
%SystemRoot%\Sysnative\cmd.exe /C ""%~f0" %*"
endlocal
goto :EOF
rem If this batch file was started (initially) with a parameter string,
rem interpret the first parameter string as application to run with
rem full path if the specified executable file exists at all.
rem Then run the application with full path and its parameters.
:RunApp
if not "%~1" == "" (
if exist "%~1" set "AppToRun=%~1"
)
"%AppToRun%" c: -enable
endlocal
6. Best solution for this task
But it turned out after I finished writing and testing the code above, writing this long answer and before posting it, reading the comment written by Richard on his answer on Open Command Window in Windows x64 mode, the best solution is most likely using the NSIS code as posted at
How do you request administrator permissions using NSIS?
And use in the command script just the few lines at bottom also posted as my answer on Open Command Window in Windows x64 mode to switch from 32-bit to 64-bit environment.
Try modifying RunasAdmin.cmd to use Sysnative instead of System32:
set winSysFolder=Sysnative
I am guessing that EWFMGR_Run.exe is launching a 32 bit cmd window and windows is forcing the c:\windows\syswow64 override on your attempted override of set winSysFolder=System32
According to this article, you should be using the Sysnative virtual folder instead.
The 'Sysnative' folder
As explained above, accessing the 64-bit System32 folder from a 32-bit application by simply inserting "\System32" in the folder path is not possible. A redirection to the SysWOW64 folder is made automatically by the system if you try that. But there is another folder name that can be used instead: Sysnative.
Sysnative is a virtual folder, a special alias, that can be used to access the 64-bit System32 folder from a 32-bit application or script. If you for example specify this folder path in your application's source code:
C:\Windows\Sysnative
the following folder path is actually used:
C:\Windows\System32
I'd like to point to an NSIS specific way about dealing with UAC and elevated rights.
If your NSIS installer needs to run anything with elevated permissions, you have to indicate that in your NSIS script like so:
RequestExecutionLevel admin
Once you do that, when you start the installer, it will pop up the UAC prompt and in succession won't have any problems running external scripts or programs which need elevated permissions.
This is pretty much in line with #5 of Mofi's answer - I still post this one as I think it boils it down to the need-to-know. NSIS seems to be the show-stopper here for you.
For reference:
NSIS - Could not write updated PATH to HKLM
I would like to run a batch file after resuming from sleep state in Windows.
If I start the batch file on command line everything works as expected.
But the batch script does not run properly as scheduled task.
What I have done:
External config file AutoMountConf.bat contains set Pass = Test
Local script file scheduleTask.bat contains
rem AutoMountConf.bat is in my intranet.
call X:\AutoMountConf.bat
start "" "C:\Program Files\TrueCrypt\TrueCrypt.exe" /auto favorites /p %Pass% /q
On command line the TrueCrypt container is mounted.
If I run the script from scheduled task I get the login screen to type the password manually.
There are two or perhaps even three issues.
The first one is set Pass = Test instead of set "Pass=Test" as Stephan reported already. For more details on how to assign a value right to an environment variable see my answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line?
The second issue is caused by the fact that network drives once mapped by a user to a drive letter and remembered in registry by Windows are automatically disconnected by Windows on user logs off and are only reconnected if the same user logs on again.
For a scheduled task it is therefore very often necessary to use UNC paths for files and folders on a shared folder in network or connect the network drive and disconnect it in the batch file itself executed as scheduled task.
It is not possible to call a batch file with UNC path. Windows does not allow that. Therefore it is necessary to connect and disconnect to network share manually in the batch file. I offer 2 solutions for this problem.
The first one is using command net use:
%SystemRoot%\System32\net.exe use X: \\ComputerName\ShareName password /user:Domain\UserName /persistent:no
if not errorlevel 1 (
call X:\AutoMountConf.bat
%SystemRoot%\System32\net.exe use X: /delete
start "" /wait "C:\Program Files\TrueCrypt\TrueCrypt.exe" /auto favorites /p %Pass% /q
)
password and /user:Domain\UserName is necessary only if the scheduled task is not executed with a user account which has the permissions to access the batch file on the remote machine. In general it is much more secure to define the scheduled task with the right user account and safe the password also for this account together with the task. Windows stores the password for the task encrypted like it does it also for the user account itself.
Run in a command prompt windows net use /? for details on the required and optional options. /persistent:no is what avoids remembering the network share in Windows registry for automatic reconnect after login by same user.
The second one is using commands pushd and popd:
pushd \\ComputerName\ShareName
if not errorlevel 1 (
call AutoMountConf.bat
popd
start "" /wait "C:\Program Files\TrueCrypt\TrueCrypt.exe" /auto favorites /p %Pass% /q
)
Please execute in a command prompt window pushd /? and read the output help to understand why this works.
But this solution requires that the user account used for the scheduled task with correct password is one which has appropriate permissions on the share on the remote computer. Password and user name can't be specified with this solution in the batch file itself.
if not errorlevel 1 means if previous command exited NOT with a value greater or equal 1 meaning if exit code of previous command is 0 and therefore command execution was successful. It can always happen that the remote machine is currently not available on network and therefore it is always good to check success on connecting to share on remote machine.
There is perhaps one more reason why Pass is not defined after running AutoMountConf.bat.
AutoMountConf.bat contains setlocal and the variable Pass is defined after this command was executed and before endlocal is executed in same batch file or implicitly called by command processor on exiting AutoMountConf.bat.
setlocal results in creating always a copy of existing environment variables and all modifications on environment variables are done on this local copy. The previous environment variables are restored on execution of (matching) endlocal or when end of a batch file is reached in which case the command processor automatically restores previous environment.
Please execute in a command prompt window setlocal /? and read the output help.
For examples to understand environment management by commands setlocal and endlocal perhaps even better see answers on Echoing a URL in Batch and Why is my cd %myVar% being ignored?
set Pass = Test
sets a variable pass<space> with the Content <space>Test. So %pass% keeps empty.
use this Syntax:
set "Pass=Test"
to avoid any unintended spaces.
So, I am trying to create a .bat to taskkill a specific program in Win7.
I am using the command:
taskkill /f /im "LCore.exe"
The .bat needs to be run as admin in order to work it seems so I have created a shortcut to it to run automatically in admin mode as specified in another thread (How to code a BAT file to always run as admin mode?).
However, when using the Microsoft Mouse and Keyboard Center to map one of my additional keys to run the shortcut it automatically runs the target of the shortcut rather than the shortcut itself which doesn't have the admin privileges needed (when selecting to map the shortcut it automatically changes the path to the target, manually setting the path returns a 'not found' error).
So basically I was wondering if there is another way that doesn't involve creating a shortcut to automatically run a .bat with elevated privileges.
#ECHO OFF
OPENFILES>NUL 2>&1
IF "%ERRORLEVEL%"=="0" GOTO :YouAreAdmin
GOTO :GetAdmin
:GetAdmin
ECHO.Set UAC = CreateObject^("Shell.Application"^) > "StartAsAdmin.vbs"
ECHO.UAC.ShellExecute "%~fs0", "", "", "runas", 1 >> "StartAsAdmin.vbs"
StartAsAdmin.vbs
DEL "StartAsAdmin.vbs"
EXIT /B
:OK
REM Your code starts here!
ECHO.
ECHO. If you see this, you have started as admin this bat file.
PAUSE>NUL
EXIT
Sorry, but I am new! :)
So first, OPENFILES command checks if you have runned program as administrator, like any command that needs administrator privileges. If you type >NUL 2>&1 after a command, CMD will hide any message from that command and will redirect error. So if you have troubles running a simple command action like OPENFILES, the only error that you can have is that batch file doesen't have administrator privileges. And if %ErrorLevel% is 0 (you have no errors running that command), it seems that you started application as administrator, so it steps to :OK label. But if %ErrorLevel% is not 0 (there is a problem), it seems that application doesen't have administrator privileges. So it will start automatly as administrator from a temporary VBScript generated by that batch file, then is started, and then deleted.
In Windows 7 you don't need to write additional scripts, because it has built-in "PowerShell" instrument. Try the following :
powershell.exe start-process taskkill.exe -verb runas -argumentlist '/f /im "LCore.exe"'
Is there a way for a batch file (in this case, running on Windows XP) to determine whether it was launched from a command line (i.e. inside a console window) or launched via the shell (e.g. by double-clicking)?
I have a script which I'd like to have pause at certain points when run via the shell, but not when run at a command line. I've seen a similar question on SO, but am unable to use the same solution for two reasons: first, whether or not it pauses needs to be dependent on multiple factors, only one of which is whether it was double-clicked. Second, I'll be distributing this script to others on my team and I can't realistically ask all of them to make registry changes which will affect all scripts.
Is this possible?
Found one :-) – After desperately thinking of what cmd might do when run interactively but not when launching a batch file directly ... I finally found one.
The pseudo-variable %cmdcmdline% contains the command line that was used to launch cmd. In case cmd was started normally this contains something akin to the following:
"C:\Windows\System32\cmd.exe"
However, when launching a batch file it looks like this:
cmd /c ""C:\Users\Me\test.cmd" "
Small demo:
#echo off
for %%x in (%cmdcmdline%) do if /i "%%~x"=="/c" set DOUBLECLICKED=1
if defined DOUBLECLICKED pause
This way of checking might not be the most robust, though, but /c should only be present as an argument if a batch file was launched directly.
Tested here on Windows 7 x64. It may or may not work, break, do something weird, eat children (might be a good thing) or bite you in the nose.
A consolidated answer, derived from much of the information found on this page (and some other stack overflow pages with similar questions). This one does not rely on detecting /c, but actually checks for the name of the script in the command line. As a result this solution will not pause if you double-clicked on another batch and then called this one; you had to double-click on this particular batch file.
:pauseIfDoubleClicked
setlocal enabledelayedexpansion
set testl=%cmdcmdline:"=%
set testr=!testl:%~nx0=!
if not "%testl%" == "%testr%" pause
The variable "testl" gets the full line of the cmd processor call, stripping out all of the pesky double quotes.
The variable "testr" takes "testl" and further strips outs the name of the current batch file name if present (which it will be if the batch file was invoked with a double-click).
The if statement sees if "testl" and "testr" are different. If yes, batch was double-clicked, so pause; if no, batch was typed in on command line (or called from another batch file), go on.
Edit: The same can be done in a single line:
echo %cmdcmdline% | findstr /i /c:"%~nx0" && set standalone=1
In plain English, this
pipes the value of %cmdcmdline% to findstr, which then searches for the current script name
%0 contains the current script name, of course only if shift has not been called beforehand
%~nx0 extracts file name and extension from %0
>NUL 2>&1 mutes findstr by redirecting any output to NUL
findstr sets a non-zero errorlevel if it can't find the substring in question
&& only executes if the preceding command returned without error
as a consequence, standalone will not be defined if the script was started from the command line
Later in the script we can do:
if defined standalone pause
One approach might be to create an autoexec.nt file in the root of c:\ that looks something like:
#set nested=%nested%Z
In your batch file, check if %nested% is "Z" - if it is "Z" then you've been double-clicked, so pause. If it's not "Z" - its going to be "ZZ" or "ZZZ" etc as CMD inherits the environment block of the parent process.
-Oisin
A little more information...
I start with a batch-file (test.cmd) that contains:
#echo %cmdcmdline%
If I double-click the "test.cmd" batch-file from within Windows Explorer, the display of echo %cmdcmdline% is:
cmd /c ""D:\Path\test.cmd" "
When executing the "test.cmd" batch-file from within a Command Prompt window, the display of
echo %cmdcmdline% depends on how the command window was started...
If I start "cmd.exe" by clicking the "Start-Orb" and "Command Prompt" or if I click "Start-Orb" and execute "cmd.exe" from the search/run box. Then I execute the "test.cmd" batch-file, the display of echo %cmdcmdline% is:
"C:\Windows\system32\cmd.exe"
Also, for me, if I click "Command Prompt" from the desktop shortcut, then execute the "test.cmd" batch-file, the display of echo %cmdcmdline% is also:
"C:\Windows\system32\cmd.exe"
But, if I "Right-Click" inside a Windows Explorer window and select "Open Command Prompt Here", then execute the "test.cmd" batch-file, the display of echo %cmdcmdline% is:
"C:\Windows\System32\cmd.exe" /k ver
So, just be careful, if you start "cmd.exe" from a shortcut that contains a "/c" in the "Target" field (unlikely), then the test in the previous example will fail to test this case properly.