Automatically running a batch file as an administrator - batch-file

How do I run a batch file from another batch file with administrator rights?
I have tried the RUNAS command, but it requires the administrator password.
I am searching for an alternative for running a batch file by right clicking on it and running as an administrator. I want to automate it from another batch file.

Put each line in cmd or all of theme in the batch file:
#echo off
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
"Put your command here"
it works fine for me.

On Windows 7:
Create a shortcut to that batch file
Right click on that shortcut file and choose Properties
Click the Advanced button to find a checkbox for running as administrator
Check the screenshot below

You can use PowerShell to run b.bat as administrator from a.bat:
set mydir=%~dp0
Powershell -Command "& { Start-Process \"%mydir%b.bat\" -verb RunAs}"
It will prompt the user with a confirmation dialog. The user chooses YES, and then b.bat will be run as administrator.

Use
runas /savecred /profile /user:Administrator whateveryouwanttorun.cmd
It will ask for the password the first time only. It will not ask for password again, unless the password is changed, etc.

If you're trying to invoke a Windows UAC prompt (the one that puts the whole screen black and asks if you're granting administrator privileges to the following task), RUNAS is not the smoothest way to do it, since:
You're not going to get prompted for UAC authorization, even if logged in as the administrator and
RUNAS expects that you have the administrator password, even if your user is setup as a local administrator, in which case the former password is not a sound security practice, specially in work environments.
Instead, try to copy & paste the following code to ensure that your batch file runs with administrator privileges:
#echo off
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' NEQ '0' (
echo Requesting Admin access...
goto goUAC )
else goto goADMIN
:goUAC
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:goADMIN
pushd "%CD%"
CD /D "%~dp0"
rem --- FROM HERE PASTE YOUR ADMIN-ENABLED BATCH SCRIPT ---
echo Stopping some Microsoft Service...
net stop sqlserveragent
rem --- END OF BATCH ----
This solution works 100% under Windows 7, 8.1 and 10 setups with UAC enabled.

Runas.exe won't work here. You can use VBScript to invoke the "Run as Administrator" shell verb. The Elevation Powertoys contain a batchfile that allows you to invoke an elevated command:
elevatecmd.exe
http://blogs.technet.com/b/elevationpowertoys/

CMD Itself does not have a function to run files as admin, but powershell does, and that powershell function can be exectuted through CMD with a certain command. Write it in command prompt to run the file you specified as admin.
powershell -command start-process -file yourfilename -verb runas
Hope it helped!

The complete solution I found that worked was:
#echo off
cd /D "%~dp0"
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
"Put your command here"
credit for:
https://stackoverflow.com/a/51472107/15087068
https://serverfault.com/a/95696

This a trick that i used if anyone wants they can try this in batch file.This will give you the admin prompt when you run the batch file
#echo off
cd \ && cd windows/system32 && command which needs admin credentials
pause

Related

using runas with a password and a sql command

I have a batch file with the following script (which i found here at stackoverflow)
#if (#CodeSection == #Batch) #then
#echo off
start runas "/user:domain\username" "cmd.exe"
CScript //nologo //E:JScript "%~F0"
goto :EOF
#end
WScript.CreateObject("WScript.Shell").SendKeys("mypass{ENTER}");
where mypass is the username's password.
this works perfectly and a new commandline window opens as the new user!
the problem is that i now need to run an sqlcmd with parameter and I can't find any way to write a batch that does both things together (open the new window as another user together with the command with parameters)
the sql command:
"C:\Program Files\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE" -S "my.server.com, 1234" -d "myDataBase" -E -b -q "EXEC myDataBase.[dbo].[myTable] #parameter=1"
I tried moving the whole sql command to another batch (myBatch.bat) file and change the first batch to this:
start runas "/user:domain\username" "myBatch.bat"
but it doesn't work.
any help please?
runas /user:domain\user "cmd.exe /k c:\path\to\mybatch.bat test"
cmd /k to keep the console open after the batch execution, or cmd /c to close it

Problems with Ampersand start as “Run as administrator”

I wonder how do I run a .bat or .cmd file as an administrator within a folder where the name contains the same Ampersand "&"? every time I try to run the file appears an error ... at what I did when I try to run as administrator cmd understand that & the folder name is a command.
Let me illustrate, I have a folder called Projects in Cmd & vbs and a file called Project 01.bat when I try to run it as administrator until an error occurs q I remove it from the folder that contains the "&"
if the Cmd & vbs.
Folder name: Cmd & Vbs
Script name: Project 01.bat
Form of execution: Option “Run as administered” in the context menu
Version of windows: 7
Example Script:
#Echo Off
Title Remover - [WMP] Buy online music
Color 4f
reg delete "HKEY_CLASSES_ROOT\SystemFileAssociations\Directory.Audio\shellex\ContextMenuHandlers\WMPShopMusic" /f>nul 2>&1
echo msgbox"Removed!",vbinformation> %temp%\Msg.vbs
start /wait %temp%\Msg.vbs>nul 2>&1
Del %temp%\Msg.vbs>nul 2>&1
Exit
Bill is correct, for DOS to work with the & character, you need to escape it using ^ an example might help:
C:\Temp>cd my&test
The system cannot find the path specified.
'test' is not recognized as an internal or external command,
operable program or batch file.
C:\Temp>cd my^&test
C:\Temp\my&test>
I discovered that this problem is in runas configuration and the correction is below:
Browse the regedit to:
HKEY_CLASSES_ROOT\batfile\shell\runas\command
HKEY_CLASSES_ROOT\cmdfile\shell\runas\command
Changes the value:
%SystemRoot%\System32\cmd.exe /C "%1" %*
To:
%SystemRoot%\System32\cmd.exe /C ""%1"" %*

Batch Script to copy contents of one folder to the other under C:\Program Files (x86) location. Not working - Acess Denied Error

I have written simple batch script, which copies contents of one folder to the other. I have already logged into the machine as Admin. I am working on windows-7 machine.
Folder 1 and Folder 2
Location of folders :
C:\Program Files (x86)\Folder1
C:\Program Files (x86)\Folder2
If i am running my script by double clicking it, i am getting Access Denied. If I right click on file "Run as Administrators" it correctly copies.
Expected Behavior:
On directly double clicking the batch script it should copy the file.As i am already logged in as Admin.
Waiting for valuable feedback, from fellow coder's
Following script, helps to run your batch file as "Run As Admin".
#echo off
if _%1_==_payload_ goto :payload
:getadmin
echo %~nx0: elevating self
set vbs=%temp%\getadmin.vbs
echo Set UAC = CreateObject^("Shell.Application"^) >> "%vbs%"
echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
goto :eof
:payload
echo %~nx0: running payload with parameters:
echo %*
echo ---------------------------------------------------
echo ADM is launching. DO NOT CLOSE THIS WINDOW.
cd /d %2
shift
shift
echo Name of the batch file which you want to run as admin
CopyFiles.bat
goto :eof
exit
May be your users group does not have Read and Execute permissions to the command processor,
please have a look at the solution described here
http://support.microsoft.com/kb/867466

Batch script to wait for file to be generated on FTP server and download

I have a program in my FTP server to generate a file, which may take 3-5 minutes to complete and also I knew the name of the file which i being created by my program. Now, once I initiate the program in my server, I have keep checking until the file is created. Once it is created, I am using the below batch script to ftp the file to my local desktop.
#ftp -i -s:"%~f0"&GOTO:EOF
open 10.100.16.111
username
password
lcd c:\
cd root/output_folder
binary
mget "*partial_file_name*" REM mget using wildcard search
disconnect
bye
This script works fine for me. But the problem is, I need modify this script as such, script should keep running until the file is generated. Because i don't know when the file creation will get completed. So, it will great if some one help/guide me to make a looping script which will wait until the completion of file creation and download the same file through FTP.
With this edit you can launch the batch file with the file name on the command line, like this:
ftpscript.bat "filename.ext"
Note that your lcd uses c:\ which is a restricted location in later versions of windows.
#echo off
>file.tmp echo open 10.100.16.111
>>file.tmp echo username
>>file.tmp echo password
>>file.tmp echo lcd c:\
>>file.tmp echo cd root/output_folder
>>file.tmp echo binary
>>file.tmp echo mget "%~1"
>>file.tmp echo disconnect
>>file.tmp echo bye
:retry
ftp -i -s:"file.tmp"
if not exist "%~1" timeout /t 300 & goto :retry
echo file has downloaded
del file.tmp
pause
More elegant solution is to use an FTP client that supports parametrized scripts or commands on command-line, such as WinSCP, to avoid creating a temporary script file.
Parametrized script
The batch file would be more or less identical as with the Windows ftp:
#echo off
:retry
winscp.com /script=script.txt /parameter "%~1"
if not exist "%~1" timeout /t 300 & goto :retry
echo file has downloaded
pause
The ftp script converts to following WinSCP script:
open ftp://username:password#10.100.16.111/
lcd c:\
cd root/output_folder
get -transfer=binary "%1%"
exit
Commands on command-line
You can also inline the commands the to the batch file:
#echo off
:retry
winscp.com /command ^
"open ftp://username:password#10.100.16.111/" ^
"lcd c:\" ^
"cd root/output_folder" ^
"get -transfer=binary ""%~1""" ^
"exit"
if not exist "%~1" timeout /t 300 & goto :retry
echo file has downloaded
pause
References:
Automating file transfers to FTP server;
Upload to multiple servers / Parametrized script.
Had you ever need to upgrade to the FTPS or the SFTP, just modify the session URL in the open command command accordingly.
(I'm the author of WinSCP)

Is it possible to run a command headlessly (in a bat script) as another user on Windows?

I want to have a .bat script do a particular task as a different user and run headlessly (no user input or prompting is allowed). Is there a way to do this with a .bat script? Please note that I am constrained to not use PowerShell as it not installed by default on all of the Windows operating systems that we must support.
I have considered RUNAS in my script, but it apparently requires interactive input.
In Linux, the equivalent idiom is:
echo "Password" | sudo -S -u username "command"
Any suggestions for Windows .bat scripts?
Update: I believe that vbscript is always available on Windows, so if a purely headless solution is available via vbscript, then that is good, too!
Here's another alternative:
wmic /user:username /password:pass process call create "cmd /c \"d:\\path\\to\\program.exe\" /arg etc"
EDIT : Apparently that doesn't allow authentication with separate credentials on the local machine.
There's a way to call runas with vbscript and have the vbscript send the password to the console to automate the password entry.
set WshShell = WScript.CreateObject("Wscript.Shell")
WshShell.run "runas /noprofile /user:USERNAME " + Chr(34) + "d:\path\to\command.exe /args" + Chr(34)
WScript.Sleep 500
WshShell.SendKeys "PASSWORD"
WshShell.SendKeys "{ENTER}"
set WshShell = nothing
Save that to a .vbs file and call it via cscript /nologo script.vbs
If you need that to run from a batch script, just do some creative echos.
#echo off
setlocal
set username=username
set password=password
set program=d:\path\to\program.exe /arg argument
echo set WshShell = WScript.CreateObject(^"Wscript.Shell^")>runas.vbs
echo WshShell.run ^"runas /netonly /noprofile /user:%username% ^" + Chr(34) + ^"%program%^" + Chr(34)>>runas.vbs
echo WScript.Sleep 500>>runas.vbs
echo WshShell.SendKeys ^"%password%^">>runas.vbs
echo WshShell.SendKeys ^"{ENTER}^">>runas.vbs
echo set WshShell = nothing>>runas.vbs
cscript /nologo runas.vbs
del /q runas.vbs
If that doesn't work for you, you could also use psexec to run a program with different credentials.
psexec -u USERNAME -p PASSWORD d:\path\to\command.exe
The only other alternative I can think of would be to run your script through a group policy startup script, which would execute the script from a system account. I also thought about calling it from the registry's HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce, but I think that might launch it from the first user who logs in after reboot.
Try the runas command.
runas /user:"DOMAIN\user" "C:\Program Files\path\to\program.exe" /savecred
You can save the credentials with /savecred, and not have to enter it another time.
http://technet.microsoft.com/en-us/library/cc771525.aspx
runas is the right way to do it. Add /username user /savecred the first time you run the batch it will ask for user's password and save it so next times it will run with the saved credential

Resources