Showing posts with label VBS. Show all posts
Showing posts with label VBS. Show all posts

Tuesday, July 4, 2017

VBScript: Task Scheduler in Windows | Task On Startup

Create your own VBScript which will execute as scheduled time or at logon time. There are different settings which will give you more control on customization of schedule task.

Then open "Task Scheduler" and follow below screenshots:


Then click "Action" and "Create Task..."


Enter your task name


Click "Trigger" and modify settings


Click "Action" and modify settings


In "Program/script" field put:
C:\Windows\System32\CScript.exe

And In "Add arguments" field put:
//Nologo //B C:\tmp\MyStartup.vbs

This will run the VBScript every 1 hour.

Now if you want to run this script when an user login then you have to change the action to "At log on", so do following as screenshot below:



Monday, June 19, 2017

VBScript: Execute Script Using Command Prompt | Execute Script Using Batch File Processing

VBScript: Execute Script Using Command Prompt | Execute Script Using Batch File Processing. It's easy to execute a VBScript file using Windows command prompt. First need to create ".vbs" file. Now create a file named "MyScript.bat" with following code and double click the bat file to execute VBScript.


@ECHO OFF
mode 200,50

cscript.exe MyScript.vbs

pause

exit;








Saturday, February 18, 2017

VBScript Take Input From User

VBScript is a scripting language to manage computer developed by Microsoft. Below is a code snippet to take user input:

Wscript.StdOut.Write "Enter Some Input: "
Source = Wscript.StdIn.ReadLine

VBScript Create Rar File With Password Protection Using WinRar.exe

VBScript is a scripting language to manage computer developed by Microsoft. Sometimes we need to create .rar file using WirRar.exe and use VBScript. Below is a code snippet to create rar file using both VBScript & WinRar.exe. There is a extension you can use password to protect your rar file. -p"PASSWORD" will create a rar file with password or if you use only -p as arguments then a prompt will appear to take password from user as input. -r use to create recursive all folders and files withing the root folder. -hs argument for include all hidden files.

Dim ObjShell, FSO
Set ObjShell = WScript.CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")

Wscript.StdOut.Write "Enter Source: "
Source = Wscript.StdIn.ReadLine

Wscript.StdOut.Write "Enter Destination: "
Destination = Wscript.StdIn.ReadLine

Wscript.StdOut.Write "Delete Source: "
DeleteSource = Wscript.StdIn.ReadLine

ObjShell.Run """C:\Program Files\WinRAR\WinRar.exe"" a -x -IBCK -ep1 -r -hs -p """ & Destination & """ """ & Source & """ ", 0, True
Set ObjShell = Nothing

Sub CheckRarCreated
    If (FSO.FileExists(Destination)) Then
       WScript.Echo Destination & " Created"
       If StrComp(DeleteSource, "True", 1) = 0 And FSO.FolderExists(Source) Then
          FSO.DeleteFolder Source
       End If
    Else
       WScript.Echo Destination & " Not Created"
    End If
End Sub
CheckRarCreated

Saturday, February 11, 2017

VBScript Open Another Program And Wait Until Closed

VBScript is a scripting language to manage computer developed by Microsoft. Below is a code snippet to open an external program suppose named "firefox.exe" and wait until firefox closed. Script will not be execute further statements until firefox closed. 

Dim objShell

ShowOption = 1
WaitUntilClose = True

Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run """C:\Program Files\Mozilla Firefox\firefox.exe""", ShowOption, WaitUntilClose
Set objShell = Nothing

'ShowOption
'0 Hide the window (and activate another window.)
'1 Activate and display the window. (restore size and position) Specify this flag when displaying a window for the first time. 
'2 Activate & minimize. 
'3 Activate & maximize. 
'4 Restore. The active window remains active. 
'5 Activate & Restore. 
'6 Minimize & activate the next top-level window in the Z order. 
'7 Minimize. The active window remains active. 
'8 Display the window in its current state. The active window remains active. 
'9 Restore & Activate. Specify this flag when restoring a minimized window. 
'10 Sets the show-state based on the state of the program that started the application.

VBScript Lunch Program Using Shell Execute

VBScript is a scripting language to manage computer developed by Microsoft. Below is a code snippet to open an external program using Shell Application.

Dim objShell

Program_Name = "Notepad.exe"
Arguments = "" 'Optional
Directory = "" 'Optional
Operation = "open" 'open,edit,find,print,properties
Show_Option = 1 

Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute Program_Name, Arguments, Directory, Operation, Show_Option

Set objShell = Nothing

'0 = Open the application with a hidden window.
'1 = Open the application with a normal window. If the window is minimized or maximized, the system restores it to its original size and position.
'2 = Open the application with a minimized window.
'3 = Open the application with a maximized window.
'4 = Open the application with its window at its most recent size and position. The active window remains active.
'5 = Open the application with its window at its current size and position.
'7 = Open the application with a minimized window. The active window remains active.
'10 = Open the application with its window in the default state specified by the application.

VBScript Launch programs whose path contains spaces

Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run("""C:\Program Files\Mozilla Firefox\firefox.exe""")
Set objShell = Nothing

Friday, February 10, 2017

VBScript Empty Recycle Bin

VBScript is a scripting language to manage computer developed by Microsoft. Now it is easy to empty your recycle bin easily. Below is a code snippet that describe how recycle bin be empty.

Const RECYCLE_BIN = &Ha&

Set FSO = CreateObject("Scripting.FileSystemObject")
Set ObjShell = CreateObject("Shell.Application")
Set ObjFolder = ObjShell.Namespace(RECYCLE_BIN)
Set ObjFolderItem = ObjFolder.Self
Wscript.Echo ObjFolderItem.Path

Set colItems = ObjFolder.Items
For Each objItem in colItems
    Wscript.Echo objItem.Name
    If (objItem.Type = "File folder") Then
        FSO.DeleteFolder(objItem.Path)
    Else
        FSO.DeleteFile(objItem.Path)
    End If
Next

VBScript Delete All Files And SubFolders

VBScript is a scripting language to manage computer developed by Microsoft. It is important that we have power to do something using some script written by me. Below is a code snippet that delete all files & subfolders & files of subfolders easily.

Set FSO = CreateObject("Scripting.FileSystemObject")
Set Folder = FSO.GetFolder("C:\tmp\xxx")

'Delete all files in root folder
for each File in Folder.Files
    On Error Resume Next
    name = File.name
    File.Delete True
    If Err Then
        WScript.Echo "Error deleting:" & Name & " - " & Err.Description
    Else
        WScript.Echo "Deleted:" & Name
    End If
    On Error GoTo 0
Next

'Delete all subfolders and files
For Each File In Folder.SubFolders
    On Error Resume Next
    name = File.name
    File.Delete True
    If Err Then
        WScript.Echo "Error deleting:" & Name & " - " & Err.Description
    Else
        WScript.Echo "Deleted:" & Name
    End If
    On Error GoTo 0
Next

Tuesday, February 7, 2017

VBScript Show Details Of a File, Copy, Delete And Move

set FSO = CreateObject("Scripting.FileSystemObject")

'Display detailed information about this file
set FileObject = FSO.GetFile("C:\tmp\heidisql.exe")

Wscript.Echo "Path = " & FileObject.Path
Wscript.Echo "Name = " & FileObject.Name
Wscript.Echo "Short Name = " & FileObject.ShortName
Wscript.Echo "Short Path = " & FileObject.ShortPath
Wscript.Echo "Drive = " & FileObject.Drive
Wscript.Echo "Size = " & FileObject.Size
Wscript.Echo "Attributes = " & FileObject.Attributes
Wscript.Echo "Parent Folder = " & FileObject.ParentFolder
Wscript.Echo "Date Created = " & FileObject.DateCreated
Wscript.Echo "Last Modified = " & FileObject.DateLastModified
Wscript.Echo "Last Accessed = " & FileObject.DateLastAccessed
'FileObject.Copy "heidisql_.exe", True 'True=Overwrite
'FileObject.Delete True 'True=Delete the read-only file
FileObject.Move "heidisql_moved.exe"

VBScript Open URL in Default Browser

Option Explicit

Dim WscriptSchell
Set WscriptSchell = CreateObject("WScript.Shell")

WscriptSchell.Run "https://google.com", 9

VBScript List And Details Of Local Drives

set FSO = CreateObject("Scripting.FileSystemObject")

'Display all drives and their properties
set ds = FSO.Drives
WScript.Echo "List of drives:"
for each d in ds
    WScript.Echo ""
    WScript.Echo "Drive Letter = " & d.DriveLetter
    WScript.Echo "Type = " & d.DriveType
    WScript.Echo "Ready = " & d.IsReady
    WScript.Echo "Path = " & d.Path
    WScript.Echo "Share Name = " & d.ShareName
    if d.IsReady then
        Details = "File System = " & d.FileSystem _
            & ", Serial = " & d.SerialNumber _
            & ", Volume = " & d.VolumeName _
            & ", Size = " & d.TotalSize _
            & ", Free = " & d.FreeSpace
        WScript.Echo Details
    end if
next

VBScript Execute Ping

Dim oShell, oExec, sLine
Set oShell = CreateObject("WScript.Shell")
Set oExec = oShell.Exec("ping google.com")

'Reading the output of the shell command thread
Do While Not oExec.StdOut.AtEndOfStream
    sLine = oExec.StdOut.ReadLine
    WScript.StdOut.WriteLine "Output: " & sLine
    WScript.Sleep 10
Loop

'Waiting for the shell command thread to end
'In case the output ends before the command
Do While oExec.Status = 0
    WScript.Sleep 100
Loop

VBScript Append text to text file if it already exists

Option Explicit

Const ForReading = 1, ForAppending = 8

Dim InputFileName, OutputFileName, FileSystemObject, InputFile, OutputFile

Set FileSystemObject = CreateObject("Scripting.FileSystemObject")
InputFileName  = "C:\tmp\input.txt"
OutputFileName = "C:\tmp\output.txt"

PreCheck

Set InputFile = FileSystemObject.OpenTextFile(InputFileName, ForReading)
Set OutputFile = FileSystemObject.OpenTextFile(OutputFileName, ForAppending, True)

OutputFile.WriteLine ""
Do While Not InputFile.AtEndOfStream 
    OutputFile.WriteLine InputFile.ReadLine
Loop

InputFile.Close
OutputFile.Close

Sub Echo(Str)
    Wscript.Echo Str
End Sub

Sub PreCheck()
    If Not FileSystemObject.FileExists(OutputFileName) Then
        Echo "Output File Not Found"
        WScript.Quit
    End If

    If Not FileSystemObject.FileExists(InputFileName) Then
        Echo "Input File Not Found"
        WScript.Quit
    End If

    If FileSystemObject.GetFile(InputFileName).Size < 1 Then
        Echo "Input File Has No Content"
        WScript.Quit
    End If
End Sub

Saturday, February 4, 2017

VBScript Clear Google Chrome Cache, History & Everything

Option Explicit
Dim FileSystemObject, RootFolder, UserName, File
Set FileSystemObject = CreateObject("Scripting.FileSystemObject")

UserName = CreateObject("WScript.Network").UserName
RootFolder = "C:\Users\" & UserName & "\AppData\Local\Google\Chrome\User Data\"
 
ProcessTerminate "chrome.exe"
DeleteFileFromFolder RootFolder

Sub DeleteFileFromFolder(Path)
    For Each File In FileSystemObject.GetFolder(Path).Files
        DeleteAllow File
    Next
    For Each File In FileSystemObject.GetFolder(Path).SubFolders
        DeleteFileFromFolder File.Path
    Next
End Sub

Sub DeleteAllow(File)
    'Bookmarks remain same
    If NOT(StrComp(Left(File.Name, 9), "Bookmarks", vbTextCompare)) = 0 Then
        Wscript.Echo File.Path + " Deleted"    
        On Error Resume Next
        FileSystemObject.DeleteFile File.Path, True
    End If
End Sub

Sub ProcessTerminate(Process)
    Const StrComputer = "." 
    Dim WshShell, ObjWMIService, ProcessList, ObjProcess
    Set WshShell = CreateObject("WScript.Shell")
    Set ObjWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & StrComputer & "\root\cimv2")

    Set ProcessList = ObjWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = '" & Process & "'")
    For Each ObjProcess in ProcessList 
        On Error Resume Next
        ObjProcess.Terminate
        Wscript.Echo "Process Terminated, ProcessId=" & ObjProcess.ProcessId & " (" & ObjProcess.Name & ")" 
    Next
End Sub

Friday, February 3, 2017

VBScript MySql connection

You have to install mysql odbc connector first.

Dim Connection, ConnectString

ConnectString = "Driver={MySQL ODBC 3.51 Driver};Server=localhost;PORT=3306;Database=database;User=root;Password="

Set Connection = CreateObject("ADODB.Connection")

Connection.Open ConnectString

Sql = "SELECT id,created_at FROM table ORDER BY id DESC LIMIT 0, 10"
Set Result = Connection.Execute(Sql)

Do Until Result.EOF
    Wscript.Echo "Id=" + CStr(Result(0)) + ",Create_Date=" & FormatDateTime(Result(1), 1)
    Result.MoveNext
Loop

Connection.Close

VBScript Get a List of the ODBC Drivers

Const HKEY_LOCAL_MACHINE = &H80000002
StrComputer = "."
Set ObjRegistry = GetObject("winmgmts:\\" & StrComputer & "\root\default:StdRegProv")
StrKeyPath = "SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers"
ObjRegistry.EnumValues HKEY_LOCAL_MACHINE, StrKeyPath, arrValueNames, arrValueTypes

For i = 0 to UBound(arrValueNames)
    StrValueName = arrValueNames(i)
    ObjRegistry.GetStringValue HKEY_LOCAL_MACHINE,StrKeyPath,StrValueName,StrValue
    Wscript.Echo StrValueName + " - " + StrValue
Next

Windows - How to terminate process using VBScript

Sub ProcessTerminate(Process)
    Const StrComputer = "." 
    Set WshShell = CreateObject("WScript.Shell")
    Set ObjWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & StrComputer & "\root\cimv2")

    Set ProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = '" & Process & "'")
    For Each ObjProcess in ProcessList 
        On Error Resume Next
        ObjProcess.Terminate
        Wscript.Echo "Process Terminated, ProcessId=" & ObjProcess.ProcessId & " (" & ObjProcess.Name & ")" 
    Next
End Sub

ProcessTerminate "chrome.exe"

VBScript Get List Of Running Processes And Executable Path

Dim Service, Process
 
Set Service = GetObject ("winmgmts:")
 
For each Process in Service.InstancesOf ("Win32_Process")
 Wscript.Echo Process.Name & ": " & Process.ExecutablePath
Next

VBScript - How to make program wait until process has finished

const DontWaitUntilFinished = false, ShowWindow = 1, DontShowWindow = 0, WaitUntilFinished = true
set WScript_Shell = WScript.CreateObject("WScript.Shell")
command1 = "C:\xampp\apache_stop.bat"
command2 = "C:\xampp\apache_start.bat"
Wscript.Echo "Apache Server Stopping"
WScript_Shell.Run command1, DontShowWindow, WaitUntilFinished
Wscript.Echo "Apache Server Stopped"
Wscript.Echo "Apache Server Starting"
WScript_Shell.Run command2, DontShowWindow, DontWaitUntilFinished
Wscript.Echo "Apache Server Started"