Is it possible to run a command without a headgear (in a bat script) as another user on Windows?
I want a .bat script to do a specific task as a different user and run without a headgear (no user input or prompt). Is there a way to do this with a .bat script? Please note that I am not allowed to use PowerShell as it is not installed by default on all Windows operating systems that we need to support.
I've looked at RUNAS in my script, but it seems to require interactive input.
On Linux, the equivalent idiom is:
echo "Password" | sudo -S -u username "command"
Any suggestions for Windows.bat scripts?
Update: I believe vbscript is always available on Windows, so if just a mute solution is available for vbscript, then that's fine too!
source to share
Here's another alternative:
wmic /user:username /password:pass process call create "cmd /c \"d:\\path\\to\\program.exe\" /arg etc"
EDIT . Apparently this prevents authentication with separate credentials on the local machine.
There is a way to call runas
with vbscript and have 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 this in a file .vbs
and call it viacscript /nologo script.vbs
If you need to run this from within a batch script, just do some creative echoes.
@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 can also use psexec to run the program with different credentials.
psexec -u USERNAME -p PASSWORD d:\path\to\command.exe
The only alternative I can think of is to run your script via a Group Policy startup script that will execute the script from the system account. I also thought about calling it from the registry HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce
, but I think it might start it on the first user to log in after a reboot.
source to share