Run VBScript as Administrator and Wait for completion - windows

I can't find a definite solution to this problem. In short, what I want to do is gather a list of applications installed on the computer, and write it to a file. Here was my first attempt:
Set objShell = WScript.CreateObject("Wscript.Shell")
randTrashVar = objShell.Run("cmd /c wmic product get Name,Version > " & strAppListPath, 0, true)
But it must be run as an admin to work in all my cases. So I tried wrapping it in runas, but don't know too much about it so I could be wrong there.
randTrashVar = objShell.Run("runas /user:Administrator ""cmd /c wmic product get Name,Version > " & strAppListPath & "", 0, true)
Or doing something with objShell.Exec too
Set getAppsProcess = objShell.Exec("runas /user:Administrator ""cmd /c wmic product get Name,Version > " & strAppListPath & "")
Do While getAppsProcess.Status = 0
WScript.Sleep 100
Loop
The first one gets me somewhere, and they all wait for the command to finish before moving on, but didn't run as admin/run at all (as far as I know).
This runs as Admin now, but no wait
CreateObject("Shell.Application").ShellExecute "cmd", "/c wmic product get Name,Version > " & strAppListPath, "", "runas", 1
What can I do to get the best of these?

One or the other. WMIC does not require admin necessarly - •
wmic
The first time you run Wmic after system installation, it must be run from an elevated command prompt. The elevated mode may not be required for subsequent executions of Wmic unless the WMI operations require administrator privilege. See http://msdn.microsoft.com/en-au/library/aa826699(v=vs.85).aspx
Start - All Programs - Accessories - Right click Command Prompt and choose Run As Administrator. Type (or copy and paste by right clicking in the Command Prompt window and choosing Paste). Type for table format
wmic /output:"%userprofile%\desktop\WindowsInstaller.html" product get /format:htable
or in a form format
wmic /output:"%userprofile%\desktop\WindowsInstaller.html" product get /format:hform
It will create a html file on the desktop.
Note
This is not a full list. This is only products installed with Windows Installer. There is no feature for everything.
However as I said in my previous post nearly everything is listed in the registry.
So to see it in a command prompt
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall /s
or in a file
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall /s>"%userprofile%\desktop\WindowsUninstall.txt"
To see it in notepad in a different format
Click Start - All Programs - Accessories - Right click Command Prompt and choose Run As Administrator. Type Regedit and navigate to
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
Right click the Uninstall key and choose Export. If you save as a reg file (there is also text file, they are slightly different text formats) you need to right click the file and choose Edit to view it.
To view Windows Updates
wmic /output:"%userprofile%\desktop\WindowsUpdate.html" qfe get /format:htable
.

Related

Run BAT as admin (w/o shortcut)

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 is possible to have RUN AS prompt for vbscript?

I have this vbscript which changes the registry values and i want it to be able to run as another account(with admin rights) in a standard windows user account. Is it possible to code it such that when u double click on the vbscript, it will ask for yr windows account name and password then u be able to run the script with that account rights?
Thanks!
In the old days you could add a runas key to the respective file type in the registry:
reg add "HKCR\VBSFile\Shell\runas\Command" /ve /t REG_EXPAND_SZ ^
/d "\"%"SystemRoot"%\system32\wscript.exe\" \"%1\" %*" /f
which would add a Run as… entry to the context menu that would prompt you for credentials.
Unfortunately, Microsoft changed the "runas" behavior when they introduced UAC. Now the registry key adds a Run as Administrator entry to the context menu, that will work only with UAC enabled.
Sysinternals to the rescue (as always): you can re-enable the context menu entry for running as a different user with ShellRunas. Download the archive, unzip the executable to a directory in your %PATH% and run ShellRunas.exe /reg to register the program. That will add a Run as different user… context menu entry for executables only, though. To add this entry for VBScript files as well you need to add the relevant registry keys/values yourself, e.g. like this:
reg add "HKCR\VBSFile\Shell\runasuser" /ve /t REG_SZ /d "#shell32.dll,-50944" /f
reg add "HKCR\VBSFile\Shell\runasuser\command" /v DelegateExecute /t REG_SZ ^
/d "{ea72d00e-4960-42fa-ba92-7792a7944c1d}" /f
or by merging a .reg file like this:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\VBSFile\Shell\runasuser]
#="#shell32.dll,-50944"
[HKEY_CLASSES_ROOT\VBSFile\Shell\runasuser\command]
"DelegateExecute"="{ea72d00e-4960-42fa-ba92-7792a7944c1d}"
There is no elegant way for incorporating this in a VBScript, though. If your system has UAC enabled, you could check if your user already has admin privileges (verification method adopted from here) and otherwise re-launch the script using the ShellExecute method with the "runas" verb:
Set reg = GetObject("winmgmts://./root/default:StdRegProv")
rc = reg.GetStringValue(&h80000003, "S-1-5-19\Environment", "TEMP", val)
If rc = 5 Then
'return code 5 == access denied
're-launch script only when it was run without arguments, so we don't go
'in circles when admin privileges can't be acquired
If WScript.Arguments.Count = 0 Then
're-launch as administrator; the additional argument is a guard to make
'sure the script is re-launched only once
CreateObject("Shell.Application").ShellExecute "wscript.exe" _
, Chr(34) & WScript.ScriptFullName & Chr(34) & " relaunch", "", "runas", 1
WScript.Quit 0
Else
WScript.Echo "Cannot acquire admin privileges."
WScript.Quit 1
End If
Else
'your code here
End If
With UAC disabled, you'd need to prompt for credentials via InputBox (bad) or with a custom password dialog (better). Either way, you'd need to re-launch the script via runas.exe
Set sh = CreateObject("WScript.Shell")
sh.Run "runas /user:" & username & " cscript """ & WScript.ScriptFullName & """"
and type in the password via SendKeys (which is a bad idea in its own right).

How to run a command on command prompt startup in Windows

EDIT
If you want to perform any task at computer startup or based on an
event this is very helpful
http://answers.microsoft.com/en-us/windows/forum/windows_7-performance/how-to-schedule-computer-to-shut-down-at-a-certain/800ed207-f630-480d-8c92-dff2313c193b
Back to the question
I have two questions:
I want some specific commands to be executed when I start command prompt.
e.g. cls to clear my command prompt.
I want to execute some commands in a batch file and wait for the user to enter new commands (if any).
e.g. A batch file which will take the user to some specified folder and then wait for the user to rename/delete a file from the command prompt.
How can I do it?
If you want a defined set of commands to run every time you start a command prompt, the best way to achieve that would be to specify an init script in the AutoRun registry value. Create it like this (an expandable string value allows you to use environment variables like %USERPROFILE%):
reg add "HKCU\Software\Microsoft\Command Processor" /v AutoRun ^
/t REG_EXPAND_SZ /d "%"USERPROFILE"%\init.cmd" /f
Then create a file init.cmd in your profile folder:
#echo off
command_A
command_B
...
cls
To remove these changes, delete the registry key:
reg delete "HKCU\Software\Microsoft\Command Processor" /v AutoRun
Make a shortcut
Go to the properties
The bit where it says: C:\Users\<Your username>\Desktop\cmd.exe, you put: -cmd /K <your command here>
e.g.
C:\Users\Lewis\Desktop\cmd.exe -cmd /K color 1f
This is the way to launch 1 command without having to mess about with the registry.
Run multiple commands
You can also use & (and) operator to execute multiple commands.
Eg.
C:\Users\Lewis\Desktop\cmd.exe -cmd /K color 1f & H: & <your command>
Credits: user6589073
I found my answer: I should use the /K switch, using which I can enter a new command on the opened command prompt.
E.g. cmd /K cls will open a command prompt for me and clear it. (Answer for question 1)
and
cmd /K MyBatchFile.bat will start a command prompt, execute the batch file and stay on the command prompt and will not exit. (Answer for question 2).
First, you need to press Windows Key + R.
In the box that appears, type "regedit" (without the quotes).
The Windows Registry Editor should open.
Now, locate to HKEY_CURRENT_USER/Software/Microsoft/Command Processor.
Once you have clicked on Command Processor on the left side, click Edit on the top bar.
Then go to New > String Value in the Edit menu.
Rename the String Value that appears to Autorun.
Right click on Autorun and select Modify.
Under the "Value Data" area, type in the commands you want to run. You can run multiple by typing && between them.
Expanding a bit, here is an alternative for Windows 10 where multiple aliases can be defined and applied to the Command Prompt upon execution.
Create a file called init.cmd containing aliases on your %USERPROFILE% folder:
init.cmd
#echo off
doskey c=cls
doskey d=cd %USERPROFILE%\Desktop
doskey e=explorer $*
doskey g=git status
doskey l=dir /a $*
Register it to be applied whenever the Command Prompt is executed:
In the Command Prompt, run:
reg add "HKCU\Software\Microsoft\Command Processor" /v AutoRun /t REG_EXPAND_SZ /d "%"USERPROFILE"%\init.cmd" /f
Done
Now the contents of init.cmd will run for executions of cmd.exe namely from:
Taskbar shortcut
WIN+R cmd
By typing cmd in the File Explorer address bar
By running cmd.exe directly from C:\Windows\System32
After registering these settings just remember to close/open:
The Command Prompt so the settings are applied
The File Explorer, if you use to launch the cmd via File Explorer address bar
To unregister it, run:
reg delete "HKCU\Software\Microsoft\Command Processor" /v AutoRun
I have a command to run a python program. I do not want to run this command manually after login, I want this command should run automatically after I logged in to my ubuntu. I am using Ubuntu 16.04.
Here is the command.
sh demo_darknet_yolov3.sh , this shell is placed in this directory littro#littro-System-Product-Name:~/MobileNet-YOLO-master/MobileNet-YOLO-master
Depending on your script, you may want to use the cmd.exe /k <input script> method instead of the registry entry Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor\autorun
I have found with the latter, that other programs that launch cmd are affected by the registry entry. For example, I cannot get Visual Studio Native Tools prompt to work properly because my script gets in the way. In my case, the script is a menu with 5 options including to launch various programs manually (I like to minimize my auto-run programs) and set various environment variables (ie., printers, proxy settings, default versions of programs, etc).
If you are doing something static I think either method works fine.
I would have commented on the question or an applicable answer, but I do not have the reputation to comment.

launch VBS script after PC startup

I want launch my simple VBS script after PC startup (Win XP). I don't want put this script in C:\Documents and Settings\%UserName%\Start Menu\Programs\Startup
I want do it in script, it is possible?
Script:<br>
Dim oShell<br>
Set oShell = WScript.CreateObject ("WScript.Shell")<br>
oShell.run "notepad.exe c:\text.txt"
You will either have to put it in the Startup folder or run it from the registry.
For all users, use registry key HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run.
For the current user, use registry key HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
In-depth
How to Automate VBScripts to run at startup.
Step 1
Click Start -> Run -> cmd or Click search and type cmd
Press enter
Type assoc .vbs in command prompt
Which should print .vbs=VBSFile
Type ftype VBSFile in command prompt
which should print:
vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
So, now you know that your vbscript files open with WScript by default.
In command-prompt, type:
reg query HKEY_CLASSES_ROOT\Applications\WScript.exe /s
If you do not see this:
HKEY_CLASSES_ROOT\Applications\WScript.exe
(Standard) REG_SZ "%SystemRoot%\System32\WScript.exe" "%1" %*
Then you need to do the following, if the above is what you see, then you can skip and go to step 3:
Step 2
Go to:
Start
Run
Type in:
regedit
Select regedit press enter (or double-click regedit) and allow the
program to make changes to your computer
Navigate to:
HKEY_CLASSES_ROOT\Applications\WScript.exe (If WScript.exe key does not exist, right-click Applications and create new key, rename it to WScript.exe)
In the empty space on the right, where there are values, right-click
and
Choose new
Select String Value
Under Name where New Value #1 is highlighted, rename by typing
(Standard)
Under Data, double click the empty value and enter the value you got
from the previous step
"%SystemRoot%\System32\WScript.exe" "%1" %*
Step 3
If you do not have regedit open,
Go to:
Start
Run
Type in:
regedit
Select app, press enter and allow the program to make changes to your computer
Else, if regedit is open, then:
Navigate to:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Right click the run folder
in the empty space on the right, where there are values, right-click
and choose new
Select Expandable String Value
Under Name where New Value #1 is highlighted, rename by typing your
own name e.g. myscript
under Data, double click the empty value and enter this
Make sure its type is REG_EXPAND_SZ, i.e. an expanded string
"%SystemRoot%\System32\WScript.exe" "C:\Users\me\myFolder\mySub-folder\myFile.vbs" "%1" %*
Restart your machine. Your vbs should run automatically
Notes:
make sure .VBS is added to the Path environment variable
if you want to use cscript instead, In step 2 type:
reg query HKEY_CLASSES_ROOT\Applications\cscript.exe /s
...instead and proceed, taking note to replace WScript with cscript where relevant
i.e. this query:
reg query HKEY_CLASSES_ROOT\Applications\cscript.exe /s
Should produce this result:
(Standard) REG_SZ "C:\Windows\System32\cscript.exe" "%1" %*
If your key and/or value is messed up you can always right-click the
messed up item and delete it. If you however want to use the
terminal, you can always follow: http://ss64.com/nt/reg.html
To check if WScript is one of the startup apps, press ctrl+alt+delete, choose the Task Manager, click on Startup. You should see Microsoft Windows Based Script Host listed.
Easy Way :
Make a bat file
WScript.exe "Path\to\your\script.vbs"
add it to startup from gpedit.msc
Just an appoinment, everybody probalby just know already.
HKLM is for any user on the machine, because means Local Machine
HKCU is just for the current user.
Add this code to the start of your vbs script
Change the end of myKey to whatever you want to call the registry key
Set WshShell = CreateObject("WScript.Shell")
myKey = "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run\MyVbsScript"
WshShell.RegWrite myKey,WScript.ScriptFullName,"REG_SZ"
Task Scheduler Alternative
No script is needed, create a new task (Task Scheduler 1.0 (learn.microsoft.com) for instruction). Then "Create a task" and populate at least these details:
New Trigger: At Login
New Action -> Action: Start A Program
Program/Script: notepad.exe
Arguments: text.txt
Start in: c:\
Software: Windows 10, Task Scheduler 1.0
you can fire a vbscipt from registry or startup by
WScript C:\somefloder\somefolder2\yourscript.vbs
you can put this line in a value on
For all the users on the machine HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
for the current user HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

msiexec quiet installation when the package is already installed

I have the following problematic scenario:
Problematic Scenrio Description Begin---------------------------
I use msiexec to install a package in quiet mode in the following way:
msiexec /i c:\mypackage.msi /quiet
Now I have the package installed. Let's say I entered the command above again:
msiexec /i c:\mypackage.msi /quiet
Problematic Scenrio Description End---------------------------
Now since the package is already installed, the installation should fail. But I have no indication for that.
I use the log option in order to get a log going:
msiexec /i c:\mypackage.msi /quiet /l* log.txt
When errors occur I do see them in the log but in the scenario depicted above the log is empty. There is also nothing written to the system event log. So my question is, How can I get an indication that the installation (The second one) didn't go?
Notes:
I am not willing to solve this problem by writing a batch script that will check if the package is installed prior to the call to msiexec. The reason is that it contradicts our customer deployment requirements.
I have a DLL custom action data, in the second time, the DLL is not activated so I can't use the DLL in order to write the failure somewhere.
Installation does not fail if the package is already installed, it was "successfully reconfigured"
In order to check if a Windows Installer package is installed on the system or not, you're best to use the Windows SDK (not a batch file) - here's a sample script that iterates the list of installed products and triggers MSIEXEC if it is not already installed. (This example searches by name, alternatively you could search by package code)
Option Explicit
Dim productName:productName = "My Awesome Product"
Dim installer : Set installer = Nothing
Set installer = Wscript.CreateObject("WindowsInstaller.Installer")
Dim productCode, property, value, message
For Each productCode In installer.Products
If InStr(1, LCase(installer.ProductInfo(productCode, "ProductName")), LCase(productName)) Then Exit For
Next
If IsEmpty(productCode) Then
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
WshShell.Exec("msiexec /i mypackage.msi /qb")
Else
Wscript.Echo productName & " is already installed."
Wscript.Quit 2
End If
Is it your package? If so, put in a prerequisite condition that checks if some key file or registry entry doesn't exist yet.
If it's not your package, wrap it in something (another installer or an exe) that will make the check.
I know this is old thread, but google hits this up and in benefit of others try this
start /wait msiexec /i c:\mypackage.msi /quiet
If error, echo %errorlevel% will be non zero. If calling above programmatically use GetLastError()

Resources