Store objShell.run in variable - windows

I am trying to store the output from a objShell.run and then display it out.
On Error Resume Next
Set objShell = CreateObject("WScript.Shell")
strPermissionsDirValue = ""
strPermissionsDirValue = objShell.run ("cacls C:\SQL2008")
WScript.Echo VBTab & strPermissionsDirValue
strPermissionsDirValue = ""
When I execute the above I get 0.
The output should be
C:\SQL2008 CREATOR OWNER:(OI)(CI)(IO)F
NT AUTHORITY\SYSTEM:(OI)(CI)F
BUILTIN\Administrators:(OI)(CI)F

The WScript.Shell object will only return numbers, based on exit status of the application you launched.
One way would be to dump the output to a temp file. Change this line..
strPermissionsDirValue = objShell.run ("cacls C:\SQL2008")
To this..
objShell.run "cmd /k cacls C:\SQL2008 > temp.txt"
Then, just read that temp file and in this case, process each line of the cacls output.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInputFile = objFSO.OpenTextFile("temp.txt", 1)
Do While objInputFile.AtEndOfStream = False
strLine = objInputFile.ReadLine
Loop

Related

Launching application using VBScript

I am trying to launch an application from the Windows shell using VBScript. The application runs without errors when run from QtCreator. However, it crashes when run from VBScript and exits with error code 255.
Here's the script:
Set objShell = WScript.CreateObject("WScript.Shell")
rv = objShell.Run("path\to\application.exe", 1 , True)
If rv <> 0 Then
MsgBox "Failed : " & rv
End If
WScript.Sleep 120000
objShell.Run "taskkill /im path\to\application.exe"
Set objShell = Nothing
Could someone please point out what I am missing?
Give a try for this vbscript and tell me the result :
Option Explicit
Dim Title,objShell,rv,ProcessPath,ProcessName
Title = "Launching and killing application using Vbcript"
Set objShell = CreateObject("WScript.Shell")
ProcessPath = "C:\Windows\system32\Calc.exe"
rv = objShell.Run(DblQuote(ProcessPath),1,False)
If rv <> 0 Then
MsgBox "Failed : " & rv
End If
Set objShell = Nothing
WScript.Sleep 12000
ProcessPath = Split(ProcessPath,"\")
ProcessName = ProcessPath(UBound(ProcessPath))
Msgbox "The Process named "& DblQuote(ProcessName) &" is being to be killed now !",_
vbExclamation,Title
Call Kill(ProcessName)
'****************************************************
Sub Kill(ProcessName)
Dim Ws,Command,Execution
Set Ws = CreateObject("Wscript.Shell")
Command = "cmd /c Taskkill /F /IM "& DblQuote(ProcessName) &""
Execution = Ws.Run(Command,0,True)
Set Ws = Nothing
End Sub
'****************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'****************************************************
Try This way :
Set objShell = WScript.CreateObject("WScript.Shell")
rv = objShell.Run(chr(34)&"c:\windows\system32\Mspaint.exe"&chr(34), 1 , False)
If rv <> 0 Then
MsgBox "Failed : " & rv
End If
WScript.Sleep 2000
objShell.Run "taskkill /f /im ""Mspaint.exe"" ",0,False
Set objShell = Nothing
I was able to find the error. I set the current directory to the folder that contains the .exe file.This is the modified script:
Option Explicit
Dim Title,objShell,rv,ProcessPath,ProcessName
Title = "Launching and killing application using Vbcript"
Set objShell = CreateObject("WScript.Shell")
objShell.CurrentDirectory = "path\to\folder\containing\.exe"
ProcessPath = "path\to\application.exe"
objShell.Run DblQuote(ProcessPath),1,False
If rv <> 0 Then
MsgBox "Failed : " & rv
End If
Set objShell = Nothing
WScript.Sleep 12000
ProcessPath = Split(ProcessPath,"\")
ProcessName = ProcessPath(UBound(ProcessPath))
Msgbox "The Process named "& DblQuote(ProcessName) &" is being to be killed now !",_
vbExclamation,Title
Call Kill(ProcessName)
Sub Kill(ProcessName)
Dim Ws,Command,Execution
Set Ws = CreateObject("Wscript.Shell")
Command = "cmd /c Taskkill /F /IM "& DblQuote(ProcessName) &""
Execution = Ws.Run(Command,0,True)
Set Ws = Nothing
End Sub
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function

Trying to create a grads script and getting error " Expected end of statement " how can I solve it?

This is a screenshot of what I'm getting the error:
The file name of the script it's coming with the grads program.
gradsgui.vbs
The content of the file the script:
' Lightweight script to call actual executables down bellow. Eventually it
' could include the same functionality of the Perl version. Now it seats in
' the very top, above Contents/
Dim objFileSystem, objFILE
' Find out where we actually are
' ------------------------------
ScriptPath = Left(WScript.ScriptFullName, _
Len(WScript.ScriptFullName) - Len(WScript.ScriptName))
' Get the current version from file
' ---------------------------------
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set objFILE = objFileSystem.OpenTextFile(ScriptPath & "Contents\Cygwin\Versions\Current#", 1)
Versions = Split(objFILE.ReadAll, vbCrLf)
Version = Left(Versions(0),Len(Versions(0))-1)
objFile.Close
Set objFileSystem = Nothing
' Actual executable path
' ----------------------
ActualPath = ScriptPath & "Contents\Cygwin\Versions\" & Version & "\i686\"
ExecutableName = Left(WScript.ScriptName,Len(WScript.ScriptName)-4) & ".exe"
ExecutableFullName = ActualPath & ExecutableName
' WScript.echo "Running <" & ExecutableFullName & ">"
' Command line arguments
' ----------------------
Set ArgObj = WScript.Arguments
sArgCount = ArgObj.Count
args = " "
For x = 0 To sArgCount - 1
args = args & " " & ArgObj(x)
Next
Set ArgObj = Nothing
Set xsize = 650 500
'Start actual application down below
'-----------------------------------
Set objShell = CreateObject("WScript.Shell")
'objShell.Run "%COMSPEC% /k" & ExecutableFullName & args
objShell.Run ExecutableFullName & args
Set objShell = Nothing
The line that I added that give the error is:
set xsize = 650 500
If I type this command in the console window when running the grads.exe it will work fine. But using the script it's giving me this error.
What i did is adding to the end of the file script two lines:
'Start actual application down below
'-----------------------------------
Set objShell = CreateObject("WScript.Shell")
Set env = objShell.Environment("PROCESS")
env("xsize") = "650 500"
' objShell.Run "%COMSPEC% /k" & ExecutableFullName & args
objShell.Run ExecutableFullName & args
Set objShell = Nothing
The lines i added are:
Set env = objShell.Environment("PROCESS")
env("xsize") = "650 500"
But they are not doing anything. It's not opening the new window in this size.
Looks like you're mixing VBScript and CMD commands here. You probably mean to set xsize=650 500 as an environment variable, but in VBScript the Set keyword is used for assigning objects to variables, not for defining variables in general like in CMD.
Try defining the variable in the process environment, so that it's inherited by the child process you're starting:
Set objShell = CreateObject("WScript.Shell")
Set env = objShell.Environment("PROCESS")
env("xsize") = "650 500"
objShell.Run ExecutableFullName & args

Read VBScript window for answer and execute into Batch

SETLOCAL ENABLEDELAYEDEXPANSION
curl "http://example.net/?u=%VARIABLE%" >> TXT.txt
wscript "C:\THAT.vbs"
start "" "http://url.com/%VARIABLE%"
exit
I have (above) batch file that runs CURL and writes output into a txt file.
And this (below) vbs file reads the content and shows message.
As you can see there is a start command in my batch file.
If I click Yes in vbs window I want to execute that start command.
If I click No in vbs window I want to go to exit.
Option Explicit
Const conForReading = 1
Dim objFSO, objReadFile, objFile, contents, result, shell, WshShell, somestring, txFldr2Open
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("TXT.txt")
If objFile.Size > 0 Then
Set objReadFile = objFSO.OpenTextFile("TXT.txt", 1, False)
contents = objReadFile.ReadAll
result = MsgBox ("HEADTEXT;" & vbCr & contents & "",vbYesNo+vbExclamation+vbSystemModal,"HEADQUESTION?")
Select Case result
Case vbYes
LET THE BATCH FILE KNOW ANSWER IS YES
Case vbNo
LET THE BATCH FILE KNOW ANSWER IS NO
End Select
objReadFile.close
Else
End If
Set objFSO = Nothing
Set objReadFile = Nothing
WScript.Quit()
It it possible to do that? If so how?
Use the exit code from vbscript to return the selection to batch script
batch file
SETLOCAL ENABLEDELAYEDEXPANSION
curl "http://example.net/?u=%VARIABLE%" >> TXT.txt
cscript //nologo "C:\THAT.vbs"
if not errorlevel 1 (
start "" "http://url.com/%VARIABLE%"
)
exit
that.vbs
Option Explicit
Const conForReading = 1
Dim objFSO, contents, result
result = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.GetFile("TXT.txt").Size > 0 Then
contents = objFSO.OpenTextFile("TXT.txt", 1, False).ReadAll
If MsgBox ("HEADTEXT;" & vbCr & contents & "",vbYesNo+vbExclamation+vbSystemModal,"HEADQUESTION?") = vbYes Then
result = 0
End If
End If
WScript.Quit result

VBS Run cmd.exe output to a variable; not text file

This is what I have so far. It works; outputing the folder path to temp to a text file.
What I really want, is to output the data to a variable. Every example I see online, show how to do this using something like:
set objScriptExec = wshShell.Exec (strCommand)
followed by
strresult = LCase(objScriptExec.StdOut.ReadAll. // code
I want this to run with Run, not Exec, because I want the command prompt windows to be hidden as I will performing many commands with the code below. How can I capture that output to a variable?
Set wsShell = CreateObject("WScript.Shell")
strCommand = "cmd /c echo %temp% > %temp%\test.txt"
wsShell.Run strcommand,0,True
This may be done with the Windows Script Host Exec command. StdOut, StdIn, and StdErr may all be accessed, and ERRORLEVEL is available when the command completes.
Dim strMessage, strScript, strStdErr, strStdOut
Dim oExec, oWshShell, intErrorLevel
Dim ComSpec
Set oWshShell = CreateObject("WScript.Shell")
ComSpec = oWshShell.ExpandEnvironmentStrings("%comspec%")
intErrorLevel = 0
strScript = ComSpec & " /C echo %temp%"
On Error Resume Next
Set oExec = oWshShell.Exec (strScript)
If (Err.Number <> 0) Then
strMessage = "Error: " & Err.Message
intErrorLevel = 1
Else
Do While oExec.Status = 0
Do While Not oExec.StdOut.AtEndOfStream
strStdOut = strStdOut & oExec.StdOut.ReadLine & vbCrLf
Loop
Do While Not oExec.StdErr.AtEndOfStream
strStdErr = strStdErr & oExec.StdErr.ReadLine & vbCrLf
Loop
WScript.Sleep 0
Loop
intErrorLevel = oExec.ExitCode
strMessage = strStdOut & strStdErr & CStr(intErrorLevel)
End If
WScript.Echo (strMessage)
NOTE: Replacing "ReadLine" above with "Read(1)" accomplishes the same thing, but adds an ability to process characters rather than whole lines.
Of course Wscript.Shell would be a lot easier, but, since you want more fine grain control of your session, consider using Win32_Process. Usually, one uses this to control the placement of a new window, but, in your case, you want it hidden, so I set startupInfo.ShowWindow = 0 which means SW_HIDE. The following declares a VBScript function called RunCmd and which will run a command in an invisible window saving the output to a text file and then return the contents of the text file to the caller. As an example, I invoke RunCmd with the HOSTNAME command:
Function RunCmd(strCmd)
Dim wmiService
Set wmiService = GetObject("winmgmts:\\.\root\cimv2")
Dim startupInfo
Set startupInfo = wmiService.Get("Win32_ProcessStartup")
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim cwd
cwd = fso.GetAbsolutePathname(".")
startupInfo.SpawnInstance_
startupInfo.ShowWindow = 0
' startupInfo.X = 50
' startupInfo.y = 50
' startupInfo.XSize = 150
' startupInfo.YSize = 50
' startupInfo.Title = "Hello"
' startupInfo.XCountChars = 36
' startupInfo.YCountChars = 1
Dim objNewProcess
Set objNewProcess = wmiService.Get("Win32_Process")
Dim intPID
Dim errRtn
errRtn = objNewProcess.Create("cmd.exe /c """ & strCmd & """ > out.txt", cwd, startupInfo, intPID)
Dim f
Set f = fso.OpenTextFile("out.txt", 1)
RunCmd = f.ReadAll
f.Close
End Function
MsgBox RunCmd("HOSTNAME")
References:
Create method of the Win32_Process class
Win32_ProcessStartup class

Computername write to txt file (%computername%)

If a computer run's the script on Wednesday, i want that it creates a %computername*.txt file in a netwok map. In batch script i can to it with %computername%.txt, what code can i use it for VBS script?
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
If DatePart("W",Date) = 4 Then
'Today is Wednesday, so run the virus scan
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("\\server\Avast Scan Log\%COMPUTERNAME%.txt")
WshShell.Run """C:\Program Files\Alwil Software\Avast4\aswcmd"" M: /m /*", , True
End If
>> WScript.Echo CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")
>>
WINXPSP3
>> WScript.Echo CreateObject("WScript.Network").Computername
>>
WINXPSP3
Use the WshNetwork object to get the computer name as suggested. It looks like this.
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
Set WshNetwork = CreateObject("WScript.Network")
strComputer = WshNetwork.ComputerName
If DatePart("W",Date) = 4 Then
'Today is Wednesday, so run the virus scan
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("\\server\Avast Scan Log\" & strComputer & ".txt")
WshShell.Run """C:\Program Files\Alwil Software\Avast4\aswcmd"" M: /m /*", , True
End If

Resources