How to launch System File Checker tool with vbs - windows

In batch or cmd, sfc.exe run with a simple command:
%windir%\system32\SFC.exe /SCANNOW
How to run this command with .vbs script (x86 x64)??
Thanks

You can do something like this, just give a try !
Option Explicit
' Run as Admin
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
Dim ws,MyCommand,Execution
Set ws = createobject("wscript.shell")
MyCommand = "SFC /SCANNOW"
Execution = ws.run(MyCommand,1,False)

Related

How to start java program (from .jar) elevated only using VBScript

There is a great answer providing a batch file what will allways do it's best to run elevated and will not elevate if already elevated.
I don't want to distribute the batch file with my program though. The whole core of the answer is this VBSScript:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "[path to the batch file which will run elevated]", "ELEV", "", "runas", 1
Pretty simple. So just instead of the path to the batch file, I want to use the path to a jar file. But it doesn't seem to work:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "AutoClient.jar", "ELEV", "", "runas", 1
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw -jar AutoClient.jar", "ELEV", "", "runas", 1
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw", "ELEV", "-jar AutoClient.jar", "runas", 1
So well, how can I run the jar from the vbs file? Both files share the same directory. It's necessary that java application's working directory is that directory.
Edit:
So thanks #MCND (and this) I now know that the arguments go as follows:
path to executable to run
command line parameters sent to the program
working directory of the new process
'runas' command which invokes elevation
0 means do not show the window, 1 to show the window
And thanks to his code:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw.exe", "-jar AutoClient.jar", "", "runas", 1
I can add another error in my collection:
The documentation states that the first parameter in the call is the file to start, leaving the arguments to the second parameter. So it should be (sorry, not tested)
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw.exe", "-jar AutoClient.jar", "", "runas", 1
So far, the only way I made this work without crazy popup errors is:
' Get the script location, the directorry where it's running
Set objShell = CreateObject("Wscript.Shell")
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
' Args:
' path to executable to run
' command line parameters - first parameter of this file, which is the jar file name
' working directory (this doesn't work but I use it nevertheless)
' runas command which invokes elevation
' 0 means do not show the window. Normally, you show the window, but not this console window
' which just blinks and disappears anyway
UAC.ShellExecute "run-normally.bat", "SomeFile.jar, strFolder, "runas", 0
Because the working directory parameter doesn't work, I have following two lines in the bat file:
rem Used as a helper for the elevating VBS script. Runs the jar file
rem given as 1st argument as if the file was double clicked.
rem Make sure we're on our CURRENT directory
cd /d %~dp0
rem Run java, expecting the jar file to be given as the 1st argument
javaw -jar %1
I am not satisfied with this solution for cosmetic reasons. I want to display the UAC message for JRE, not windows command line:
I don't use Java but you aren't specifing full paths. You can't expect things to work reliably. Also whatever you are starting will need to have on it's right click menu Run As Administrator because the VBS code runs that menu command as if you clicked it. If it's not there you can't click it. EXE have it. So specify the correct paths to both Javaw and the jar file.
One issue is that the current directory is different depending on what technique you are using. ALWAYS specify full paths.
Here's a script that lists what verbs are available for an object (not we are not working with files but with objects). The graphical shell (explorer) is an object browser and has no idea what a file is apart from the fact it's an object of some type.
---------------------------
Windows Script Host
---------------------------
ShVerb
Lists or runs an explorer verb (right click menu) on a file or folder
ShVerb <filename> [verb]
Used without a verb it lists the verbs available for the file or folder
The program lists most verbs but only ones above the first separator
of the menu work when used this way
The Properties verb can be used. However the program has to keep running
to hold the properties dialog open. It keeps running by displaying
a message box.
---------------------------
OK
---------------------------
The script
HelpMsg = vbcrlf & " ShVerb" & vbcrlf & vbcrlf & " David Candy 2014" & vbcrlf & vbcrlf & " Lists or runs an explorer verb (right click menu) on a file or folder" & vbcrlf & vbcrlf & " ShVerb <filename> [verb]" & vbcrlf & vbcrlf & " Used without a verb it lists the verbs available for the file or folder" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The program lists most verbs but only ones above the first separator" & vbcrlf & " of the menu work when used this way" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The Properties verb can be used. However the program has to keep running" & vbcrlf & " to hold the properties dialog open. It keeps running by displaying" & vbcrlf & " a message box."
Set objShell = CreateObject("Shell.Application")
Set Ag = WScript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
If Ag.count = 0 then
wscript.echo " ShVerb - No file specified"
wscript.echo HelpMsg
wscript.quit
Else If Ag.count = 1 then
If LCase(Replace(Ag(0),"-", "/")) = "/h" or Replace(Ag(0),"-", "/") = "/?" then
wscript.echo HelpMsg
wscript.quit
End If
ElseIf Ag.count > 2 then
wscript.echo vbcrlf & " ShVerb - To many parameters" & vbcrlf & " Use quotes around filenames and verbs containing spaces" & vbcrlf
wscript.echo HelpMsg
wscript.quit
End If
If fso.DriveExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetFileName(Ag(0)))
' Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Set objFolderItem = objFolder.self
msgbox ag(0)
ElseIf fso.FolderExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
ElseIf fso.fileExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Else
wscript.echo " ShVerb - " & Ag(0) & " not found"
wscript.echo HelpMsg
wscript.quit
End If
Set objVerbs = objFolderItem.Verbs
'If only one argument list verbs for that item
If Ag.count = 1 then
For Each cmd in objFolderItem.Verbs
If len(cmd) <> 0 then CmdList = CmdList & vbcrlf & replace(cmd.name, "&", "")
Next
wscript.echo mid(CmdList, 2)
'If two arguments do verbs for that item
ElseIf Ag.count = 2 then
For Each cmd in objFolderItem.Verbs
If lcase(replace(cmd, "&", "")) = LCase(Ag(1)) then
wscript.echo(Cmd.doit)
Exit For
End If
Next
'Properties is special cased. Script has to stay running for Properties dialog to show.
If Lcase(Ag(1)) = "properties" then
WSHShell.AppActivate(ObjFolderItem.Name & " Properties")
msgbox "This message box has to stay open to keep the " & ObjFolderItem.Name & " Properties dialog open."
End If
End If
End If

Run cmd from vbscript silently

I created the following runas.vbs script:
**************
Option explicit
Dim oShell, k
Const PASSWORD = "Pass123~"
set oShell= Wscript.CreateObject("WScript.Shell")
WScript.Sleep 500
oShell.run("RunAs /noprofile /user:%computername%\postgres " & Chr(34) & "cmd /c\" &
Chr(34) & WScript.Arguments(0) & "\" & Chr(34) & Chr(34))
WScript.Sleep 1000
For k=1 To Len(PASSWORD)
WScript.Sleep 200
oShell.SendKeys Mid(PASSWORD,k,1)
Next
Wscript.Quit
**************
I use this vbscript in a Batch file to run initdb.exe (Postgresql).
Used as:
cscript //Nologo //B runasNSPostgres.vbs ""%LG_PATH%\initdb.exe" --locale=C --encoding=UTF-8 -U %DBADMIN% -D "%DBDATA%""
When this command is executed, another command prompt screen opens up which starts the initdb processing. I do not want the new cmd prompt screen to show up. I want the initdb.exe to run in the background.
If you hide the command prompt window, you won't be able to use SendKeys to send it your password keystrokes.
You can use another method, though. Try using the ECHO command and pipe its output to RunAs.
oShell.Run "echo " & PASSWORD & " | runas /noprofile ...", 0
Use a 0 as the 2nd parameter to prevent the window from appearing.

VB script + automate CLI command by VB script

I write the following VB script in order to run the CLI command - vpnclient.exe
my target is to automate the vpnclcient process and answer “y” when question appears,
I have WIN XP PC
During running the vpnclient.exe in CMD window we get then following question
Do you wish to continue? (y/n):
In my VB I write the “echo y” in order to answer on this question automatically
but question is still stuck in CMD window ,and I cant continue
please advice what chuld be wrong in my code and how to fix it?
MY VB script (vpnclient.exe – exist under VPN directory)
Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")
oShell.run "cmd /K CD C:\Program Files\Cisco\VPN & ( echo y | vpnclient.exe connect ""site moon"" )"
Set oShell = Nothing
You can try by creating a file with the commands to be executed on the command line instead of echoing the password.
Here's an example where a text file is created first with the required command and then those commands are invoked from the file.
Public Function FTPDownload(serverName, ftpuser, ftppassword, dirPath, localpath, fileName)
Dim fso, myfile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create FTP.EXE commands file
Set fso = CreateObject("Scripting.FileSystemObject")
Set myfile= fso.OpenTextFile("C:\Regression\Results\ftp_cmd.ini", 2, True)
myfile.WriteLine("open " &serverName )
myfile.WriteLine(ftpuser)
myfile.WriteLine(ftppassword)
myfile.WriteLine("lcd " & localpath )
myfile.WriteLine("cd " & dirPath)
myfile.WriteLine("prompt")
myfile.WriteLine("cr")
myfile.WriteLine("mget *" &fileName &"*" )
myfile.WriteLine("mdelete *" &fileName &"*" )
myfile.WriteLine("close")
myfile.WriteLine("quit")
myfile.Close
'====================The following code executes the FTP script. It creates a Shell object and run FTP program on top of it.===================
Set objShell = CreateObject( "WScript.Shell" )
objShell.Run ("ftp -i -s:" & chr(34) & "C:\Regression\Results\ftp_cmd.ini" & chr(34))
Set objShell = Nothing
End Function

Permission elevation from VBScript

We run Dynamics GP. Because of the way it stores forms/reports, I need to have some install scripts that copy a .SET file into the program directory. This can be done manually, but it's much quicker to just have a user run an installer script which installs the proper files for them.
I've been building a VBScript installer that copies the necessary files around. The tricky part is that some clients are running Windows XP, and some are running Windows 7 (or even 8). UAC is enabled, so permissions come into play.
The way I've tried to do it is by blindly attempting to copy the files, and if a permission error is detected, it relaunches the script with administrator permissions. Where we've run into problems is some (all?) Windows 7 machines have virtualized file/registry writes enabled, so when the script tries to copy files into C:\Program Files\Microsoft Dynamics\GP2010, it silently fails and copies them to the user's AppData\Local\VirtualStore directory. This doesn't work properly with GP.
So what I need to do is have the script copy the files to C:\Program Files (not the VirtualStore directory), and elevate permissions only if necessary. If I have it elevate across the board, this causes the Windows XP machines to simply pop up a cryptic "Run As" dialog box when launching the script.
Here's what I have so far:
Dim WSHShell, FSO, Desktop, DesktopPath
Set FSO = CreateObject("Scripting.FileSystemObject")
Set WSHShell = CreateObject("WScript.Shell")
Desktop = WSHShell.SpecialFolders("Desktop")
DesktopPath = FSO.GetAbsolutePathName(Desktop)
'Set working directory to directory the script is in.
'This ends up being C:\Windows\System32 if the script is
'started from ShellExecute, or a link in an email, thus breaking
'relative paths.
WSHShell.CurrentDirectory = FSO.GetFile(WScript.ScriptFullName).ParentFolder
On Error Resume Next
If FSO.FolderExists("C:\Program Files (x86)") Then
WScript.Echo "Installing 64-bit."
FSO.CopyFile "64-bit\*.set", "C:\Program Files (x86)\Microsoft Dynamics\GP2010\", True
FSO.CopyFile "64-bit\*.lnk", DesktopPath, True
ElseIf FSO.FolderExists("C:\Program Files\Microsoft Dynamics\GP2010\Mekorma MICR") Then
WScript.Echo "Installing 32-bit (with MICR)."
FSO.CopyFile "32-bit MICR\*.set", "C:\Program Files\Microsoft Dynamics\GP2010\", True
FSO.CopyFile "32-bit MICR\*.lnk", DesktopPath, True
Else
WScript.Echo "Installing 32-bit."
FSO.CopyFile "32-bit\*.SET", "C:\Program Files\Microsoft Dynamics\GP2010\", True
FSO.CopyFile "32-bit\*.lnk", DesktopPath, True
End If
If Err.Number = 70 Then
CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """" , "", "runas", 1
WScript.Quit
ElseIf Err.Number <> 0 Then
MsgBox "Error " & Err.Number & vbCrLf & Err.Source & vbCrLf & Err.Description
Else
MsgBox "Installed successfully."
End If
In summary: How do I have a VBScript elevate permissions without causing XP to stall at a "Run As" dialog box, and without causing Windows 7 to copy the files to AppData\Local\VirtualStore instead?
Improved on #db2 answer:
real elevation testing, without depending on passed arguments
passes all original arguments to the elevated script
uses the same host of the initial script: wscript.exe, cscript.exe, whatever
Code:
Set OSList = GetObject("winmgmts:").InstancesOf("Win32_OperatingSystem")
For Each OS In OSList
If InStr(1, OS.Caption, "XP") = 0 And InStr(1, OS.Caption, "Server 2003") = 0 Then
With CreateObject("WScript.Shell")
IsElevated = .Run("cmd.exe /c ""whoami /groups|findstr S-1-16-12288""", 0, true) = 0
If Not IsElevated Then
Dim AllArgs
For Each Arg In WScript.Arguments
If InStr( Arg, " " ) Then Arg = """" & Arg & """"
AllArgs = AllArgs & " " & Arg
Next
Command = """" & WScript.ScriptFullName & """" & AllArgs
With CreateObject("Shell.Application")
.ShellExecute WScript.FullName, " //nologo " & Command, "", "runas", 1
WScript.Echo WScript.FullName & " //nologo " & Command
End With
WScript.Quit
End If
End With
End If
Next
' Place code to run elevated here
Seems like this is the simplest way to do it.
Check OS version.
If it's not XP or 2003 (I don't anticipate this running on anything older), re-execute with elevation.
Here's the code block I added to the beginning of the script:
Dim OSList, OS, UAC
UAC = False
If WScript.Arguments.Count >= 1 Then
If WScript.Arguments.Item(0) = "elevated" Then UAC = True
End If
If Not(UAC) Then
Set OSList = GetObject("winmgmts:").InstancesOf("Win32_OperatingSystem")
For Each OS In OSList
If InStr(1, OS.Caption, "XP") = 0 And InStr(1, OS.Caption, "Server 2003") = 0 Then
CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ elevated" , "", "runas", 1
WScript.Quit
End If
Next
End If

VBscript and CMD writing into a text file

I am writing a script that executes and write everything to the file
here is example,
I stored the complete command in the variable 'Command' ,
Command = "ftp ftp.xyz.com 21 " & vbCRLF
and then executing it in command prompt,
shell.Run "%comspec% /c FTP " & Command & " > " & E:/abc.txt, 0, TRUE
but when this program execute it won't write anything to the text file because this is an incomplete command, this command on execution prompt user to input username and password of FTP,
how can i do this , that my programm automatically input username and password when prompt and then write everything to file ?
You need to run FTP using an unattended script. (Try ftp /? and look at the -s switch.)
It looks like this:
Const HOSTNAME = "ftp.myserver.com"
Const USERNAME = "Login"
Const PASSWORD = "password"
Set WshShell = CreateObject("WScript.Shell")
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFile = objFso.CreateTextFile("session.txt")
With objFile
.WriteLine "USER username"
.WriteLine "password"
.WriteLine "cd /public_html/" ' continue adding commands like this
.Close
End With
strOutput = "C:\somefilepath\output.txt"
strCommand = "%systemroot%\System32\ftp.exe -s:session.txt > " & strOutput
strCommand = WshShell.ExpandEnvironmentStrings(strCommand)
WshShell.Run strCommand, 0, vbTrue
objFso.DeleteFile "session.txt", vbTrue
You can read more in my article Using FTP in WSH on ASP Free. I also answered a related question here.

Resources