Archive - January 2012
"Successful people are always looking for opportunities to help others." - Brian Tracy
Index
Bold Specific Word in Doc
Deleting Temps
Find and Replace String in Text File
List All Open IE URLS
Add a Background Picture to Excel
Shortcut Maximize
Shortcut Fullscreen
Network Disconnect Notify
Move files, Perform MD5, Delete files
Pause Printing
Get Notified
Return User SID
Some Silent Switches
Δ
Tuesday, January 31st, 2012
Δ
Bold Specific Word in Doc
How to scriptomatically bold a specific word in entire MS Word Doc
[download resource files]
Demo
This will scan a Word document performing a bold on the specified word.
Set objShell = CreateObject("Wscript.Shell") Const wdReplaceAll = 2 varWord = "Eddie" varDocToScan = "bold.doc" ' or .docx Set objWord = CreateObject("Word.Application") objWord.Visible = True strCurrentDirectory = objShell.CurrentDirectory Set objDoc = objWord.Documents.Open(strCurrentDirectory & "\" & varDocToScan) Set objSelection = objWord.Selection objSelection.Find.Text = varWord objSelection.Find.Forward = TRUE objSelection.Find.MatchWholeWord = TRUE objSelection.Find.Replacement.Font.Bold = True objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll
Δ
[email me]
Δ
Friday, January 27th, 2012
Δ
Deleting Temps
How to delete temp files using VBScript
[download resource files]
This will delete temps in both XP and Win7. It also deletes contents of subfolders as well.
Option Explicit on error resume next Dim objShell Dim objSysEnv,objUserEnv Dim strUserTemp Dim strSysTemp Dim userProfile,TempInternetFiles Dim OSType Set objShell=CreateObject("WScript.Shell") Set objSysEnv=objShell.Environment("System") Set objUserEnv=objShell.Environment("User") strUserTemp= objShell.ExpandEnvironmentStrings(objUserEnv("TEMP")) strSysTemp= objShell.ExpandEnvironmentStrings(objSysEnv("TEMP")) userProfile = objShell.ExpandEnvironmentStrings("%userprofile%") DeleteTemp strUserTemp 'delete user temp files DeleteTemp strSysTemp 'delete system temp files 'delete Internet Temp files 'the Internet Temp files path is diffrent according to OS Type OSType=FindOSType 'msgbox OSType If OSType="Windows 7" Or OSType="Windows Vista" Then TempInternetFiles=userProfile & "\AppData\Local\Microsoft\Windows\Temporary Internet Files" ElseIf OSType="Windows 2003" Or OSType="Windows XP" Then TempInternetFiles=userProfile & "\Local Settings\Temporary Internet Files" End If DeleteTemp TempInternetFiles 'this is also to delete Content.IE5 in Internet Temp files TempInternetFiles=TempInternetFiles & "\Content.IE5" DeleteTemp TempInternetFiles WScript.Quit Sub DeleteTemp (strTempPath) On Error Resume Next Dim objFSO Dim objFolder,objDir Dim objFile Dim i Set objFSO=CreateObject("Scripting.FileSystemObject") Set objFolder=objFSO.GetFolder(strTempPath) 'delete all files For Each objFile In objFolder.Files objFile.delete True Next 'delete all subfolders For i=0 To 10 For Each objDir In objFolder.SubFolders objDir.Delete True Next Next 'clear all objects Set objFSO=Nothing Set objFolder=Nothing Set objDir=Nothing Set objFile=Nothing End Sub Function FindOSType 'Defining Variables Dim objWMI, objItem, colItems Dim OSVersion, OSName Dim ComputerName ComputerName="." 'Get the WMI object and query results Set objWMI = GetObject("winmgmts:\\" & ComputerName & "\root\cimv2") Set colItems = objWMI.ExecQuery("Select * from Win32_OperatingSystem",,48) 'Get the OS version number (first two) and OS product type (server or desktop) For Each objItem in colItems OSVersion = Left(objItem.Version,3) Next Select Case OSVersion Case "6.1" OSName = "Windows 7" Case "6.0" OSName = "Windows Vista" Case "5.2" OSName = "Windows 2003" Case "5.1" OSName = "Windows XP" Case "5.0" OSName = "Windows 2000" End Select 'Return the OS name FindOSType = OSName 'Clear the memory Set colItems = Nothing Set objWMI = Nothing End Function
Δ
[email me]
Δ
Wednesday, January 25th, 2012
Δ
Find and Replace String in Text File
How to find and replace a specified string in a text file; vbscript.
[download resource files]
Demo
This will search a text file, replacing the specified string. It uses read and write functionality
of VBScript.
Set objShell = CreateObject("Wscript.Shell") strCurrentDirectory = objShell.CurrentDirectory varFind = "Eddie" varReplace = "Jackson" varDocToScan = "Find_and_Replace.txt" Const ForReading = 1 Const ForWriting = 2 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(strCurrentDirectory & "\" & varDocToScan, ForReading) strText = objFile.ReadAll objFile.Close strNewText = Replace(strText, varFind, varReplace) Set objFile = objFSO.OpenTextFile(strCurrentDirectory & "\" & varDocToScan, ForWriting) objFile.WriteLine strNewText objFile.Close
Δ
[email me]
Δ
Tuesday, January 24th, 2012
Δ
List All Open IE URLS
How to list the URLs of all open IE browser windows
[download resource files]
Demo
If you happen to have multiple IE Browsers open, this can list what URLs are currently open
in those browsers. Could be used for tracking URLs.
Dim oShell : Set oShell = CreateObject("Shell.Application") Dim oIEApp : Set oIEApp = CreateObject("InternetExplorer.Application") Dim oShellWindows : Set oShellWindows = oShell.windows For Each oIEApp in oShellWindows If Right(LCase(oIEApp.Fullname),12) = "iexplore.exe" then If Len(oIEApp.LocationURL) > 0 then msgbox oIEApp.LocationURL End if End if Next
Δ
[email me]
Δ
Monday, January 23rd, 2012
Δ
Add a Background Picture to Excel
How to add any picture to the background of an Excel Worksheet
[download resource files]
Demo
Add your favorite picture as a background to your Excel worksheet.
Set objExcel = CreateObject("Excel.Application") Set objShell = CreateObject("Wscript.Shell") varPicture = "Add a Background logo.jpg" objExcel.Visible = True Set objWorkbook = objExcel.Workbooks.Add Set objWorksheet = objWorkbook.Worksheets(1) strCurrentDirectory = objShell.CurrentDirectory FullPath = strCurrentDirectory & "\" & varPicture objWorksheet.SetBackgroundPicture FullPath
Δ
[email me]
Δ
Tuesday, January 17th, 2012
Δ
Shortcut Maximize
How to maximize IE via a shortcut
[download resource files]
Simple script to always maximize a particular shortcut.
Option Explicit Dim URL, objIE, Maximize Set objIE=WScript.createobject("internetexplorer.application","objIE") Set Maximize = WScript.CreateObject("WScript.Shell") URL = "http://www.google.com" objIE.visible = True objIE.TheaterMode = False objIE.AddressBar = True objIE.StatusBar = True objIE.MenuBar = True objIE.FullScreen = False objIE.Navigate(URL) WScript.Sleep 1000 Maximize.SendKeys "{F11}" WScript.Quit(0)
Δ
[email me]
Δ
Monday, January 16th, 2012
Δ
Shortcut Fullscreen
How to create IE fullscreen shortcut
[download resource files]
Simple script to always open a particular shortcut in full screen.
Option Explicit Dim URL, objIE, Maximize Set objIE=WScript.createobject("internetexplorer.application","objIE") Set Maximize = WScript.CreateObject("WScript.Shell") URL = "http://www.google.com" objIE.visible = True objIE.TheaterMode = False objIE.AddressBar = True objIE.StatusBar = True objIE.MenuBar = True objIE.FullScreen = True objIE.Navigate(URL) 'WScript.Sleep 1000 'Maximize.SendKeys "{F11}" WScript.Quit(0)
Δ
[email me]
Δ
Wednesday, January 11th, 2012
Δ
Network Disconnect Notify
How to create a popup when the network has lost connection
[download resource files]
Demo
Get notified when you have lost network connectivity.
strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\wmi") Set colMonitoredEvents = objWMIService.ExecNotificationQuery _ ("Select * from MSNdis_StatusMediaDisconnect") Do While True Set strLatestEvent = colMonitoredEvents.NextEvent Wscript.Echo "A network connection has been lost:" WScript.Echo strLatestEvent.InstanceName, Now Wscript.Echo Loop
Δ
[email me]
Δ
Tuesday, January 10th, 2012
Δ
Move files, Perform MD5, Delete files
How to create your own archive script
[download resource files]
This allows you to copy, check MD5, then delete files if they pass the MD5 check.
Note that it uses checksum.exe and robocopy.exe. Great for archiving.
:: E L I T E S O L U T I O N S :: SCRIPT LANGUAGE: BATCH SHELL :: SCRIPT NAME: SYNC.CMD :: PURPOSE: TO BE USED TO COPY FILES FROM ONE SERVER TO THE NEXT,AND THEN :: PERFORM CHECKSUM - DELETE FILES THAT HAVE SUCCESSFUL CRCS :: CREATION DATE: 01/10/2012 :: DIRECTIONS: ADD SOURCE AND DESTINATION PATHS TO SCRIPT. LAUNCH SCRIPT. :: AUTHOR: EDDIE JACKSON - SOFTWARE PACKAGING ENGINEER :: EMAIL: MRNETTEK2000@YAHOO.COM :: ADD REQUIRED FILES TO SYSTEM32: FC.EXE, ROBOCOPY.EXE, CHECKSUM.EXE @echo off Title Administrative Copy with Checksum by Eddie Jackson color 0a Setlocal EnableDelayedExpansion rem enter source path here set path1=\\myserver01\upload\site01 rem example \\SERVERNAME\SHARENAME1 rem enter destination path here set path2=\\myserver02\upload\site02 rem example \\SERVERNAME\SHARENAME2 rem do not edit below this line rem -------------------------------------- rem internal variables set %%g= set %%i= set errorlevel= set %errorlevel%= cls echo Checking requirements... if not exist "%path1%\" md "%path1%" if not exist "%path2%\" md "%path2%" if not exist "%path1%\" exit /b if not exist "%path2%\" exit /b if not exist "%path2%\__REPORTS\" md "%path2%\__REPORTS" if exist "%path2%\filesnew.txt" del /q "%path2%\filesnew.txt" if exist "%path2%\filesnew.txt" del /q "%path2%\files.txt" if exist "%temp%\remove.txt" del /q "%temp%\remove.txt" %windir%\system32\ping.exe -n 2 127.0.0.1>nul REM REPORT: LIST ENTIRE FOLDER & FILE LIST cls echo Creating working file list... %windir%\system32\ping.exe -n 5 127.0.0.1>nul dir /s /b "%path1%">"%path2%\files.txt" REM CREATES DATE AND TIME TIMESTAMP for /F "tokens=2-4 delims=/- " %%p in ('date/T') do set mdate=%%r%%p%%q for /F "tokens=1-2 delims=:- " %%p in ('time/T') do set mtime=%%p%%q REM REPORT: LIST ENTIRE FOLDER & FILE LIST cls echo CREATING REPORT: All Files Before Snapshot... %windir%\system32\ping.exe -n 5 127.0.0.1>nul dir /s /q "%path1%">"%path2%\__REPORTS\%mdate%_%mtime%_REPORT_ALL_FILES_BEFORE_SNAPSHOT.txt" REM FIRST PASS REM PRIMARY COPY FUNCTION cls echo Copy all files and folders using robocopy... echo Copying from %path1% to %path2% %windir%\system32\ping.exe -n 5 127.0.0.1>nul %windir%\system32\robocopy.exe "%path1%" "%path2%" "*.*" /E /SEC /R:3 /W:5 cls echo Robocopy is complete. %windir%\system32\ping.exe -n 5 127.0.0.1>nul echo. REM SECOND PASS REM CREATES FOLDER STRUCTURE cls echo Creating Folder Structure via XCopy... %windir%\system32\ping.exe -n 5 127.0.0.1>nul %windir%\system32\xcopy.exe "%path1%" "%path2%" /f /s /c /h /d /t /i /r /y /z cls echo Folder Structure via XCopy is complete. %windir%\system32\ping.exe -n 5 127.0.0.1>nul echo. REM REMOVES PATH NAME FROM FILES.TXT for /f "tokens=* delims= " %%g in (%path2%\files.txt) do ( set _test=%%g set _str=!_test:%path1%\=! echo !_str!>> %path2%\filesnew.txt ) echo aaa> "%path2%\md5a.txt" echo bbb> "%path2%\md5b.txt" rem cls rem echo Change files to force CRC failures... rem pause REM CRC FUNCTION %windir%\system32\ping.exe -n 5 127.0.0.1>nul for /f "tokens=* delims=" %%i in (%path2%\filesnew.txt) do ( cls echo Performing CRC... echo. echo File01: "%path1%\%%i" echo File02: "%path2%\%%i" echo. echo aaa> "%path2%\md5a.txt" echo bbb> "%path2%\md5b.txt" %windir%\system32\checksum.exe -a md5 -o "%path2%\md5a.txt" "%path1%\%%i" && %windir%\system32\checksum.exe -a md5 -o "%path2%\md5b.txt" "%path2%\%%i" rem if checksum returns error: md5a and md5b become contrast files if errorlevel 1 (echo aaa> "%path2%\md5a.txt") & (echo bbb> "%path2%\md5b.txt") & (echo Failed MD5 - DO NOT DELETE) rem if checksum returns success: perform file comparison - if files match DELETE FILE if errorlevel 0 (%windir%\system32\fc.exe "%path2%\MD5a.txt" "%path2%\MD5b.txt" && if errorlevel 0 del /q "%path1%\%%i" && echo Passed MD5 - DELETE FILE) rem if files do not match, DO NOT DELETE if errorlevel 1 (echo Failed MD5 - DO NOT DELETE) rem copy to be tested further rem if errorlevel 1 copy /y /v "%path1%\%%i" "%path2%\%%i" rem basic info echo ---------------------- echo path1: %path1%\ echo path2: %path2%\ echo filename: %%i echo ---------------------- ) ) REM CREATES DATE AND TIME TIMESTAMP for /F "tokens=2-4 delims=/- " %%p in ('date/T') do set mdate=%%r%%p%%q for /F "tokens=1-2 delims=:- " %%p in ('time/T') do set mtime=%%p%%q REM REPORT cls echo CREATING REPORT: All Files After Snapshot... dir /s /q %path2%>"%path2%\__REPORTS\%mdate%_%mtime%_REPORT_ALL_FILES_AFTER_SNAPSHOT.txt" REM CLEANUP cls echo Performing cleanup... %windir%\system32\ping.exe -n 4 127.0.0.1>nul for /f "tokens=*" %%a in ('dir /ad/b/s "%path1%" ^| sort /R') do rd /q "%%a" dir /ad /b /s "%path1%" ^| sort /R>%temp%\remove.txt for /f "tokens=* delims=" %%b in (%temp%\remove.txt) do ( %windir%\system32\attrib.exe -s -r -h -i "%%b\Thumbs.db" del /q /f "%%b\Thumbs.db" del /q /f "%%b\Thumbs.db" rd /q "%%b" ) dir /ad /b /s "%path1%" ^| sort /R>%temp%\remove.txt for /f "tokens=* delims=" %%b in (%temp%\remove.txt) do ( %windir%\system32\attrib.exe -s -r -h -i "%%b\Thumbs.db" del /q /f "%%b\Thumbs.db" del /q /f "%%b\Thumbs.db" rd /q "%%b" ) if exist "%path2%\files.txt" del /q "%path2%\files.txt" if exist "%path2%\files.txt" del /q "%path2%\files.txt" if exist "%path2%\filesnew.txt" del /q "%path2%\filesnew.txt" if exist "%path2%\filesnew.txt" del /q "%path2%\filesnew.txt" if exist "%path2%\md5a.txt" del /q "%path2%\md5a.txt" if exist "%path2%\md5b.txt" del /q "%path2%\md5b.txt" if exist "%temp%\remove.txt" del /q "%temp%\remove.txt" set %%g= set %%i= set %%a= set %%b= set %%r= set %%p= set %%q= set path1= set path2= set errorlevel= endlocal exit /b 0
Δ
[email me]
Δ
Monday, January 9th, 2012
Δ
Pause Printing
How to pause printing
[download resource files]
Pauses a specified printer.
Option Explicit Dim arrStatus Dim blnDefault, blnPaused Dim intJobs, intStatus Dim colPrinters, colPrintJobs, objItem, objWMIService Dim strPrinter arrStatus = Array( "Script Error", "Other", "Unknown", "Idle", "Printing", "Warmup", "Stopped Printing", "Offline", "Paused", "Error", "Busy", "Not Available", "Waiting", "Processing", "Initialization", "Power Save", "Pending Deletion", "I/O Active", "Manual Feed" ) With WScript.Arguments If .Count <> 1 Then Syntax If .Named.Exists( "Default" ) Or .Named.Exists( "D" ) Then blnDefault = True Else blnDefault = False If .Unnamed.Count <> 1 Then Syntax strPrinter = .Unnamed( 0 ) End If End With Set objWMIService = GetObject("winmgmts://./root/CIMV2") Set colPrintJobs = objWMIService.ExecQuery( "SELECT * FROM Win32_PrintJob WHERE Name LIKE '" & strPrinter & ", %'", "WQL", 48 ) intJobs = 0 For Each objItem In colPrintJobs intJobs = intJobs + 1 Next If blnDefault Then Set colPrinters = objWMIService.ExecQuery( "SELECT * FROM Win32_Printer WHERE Default=TRUE", "WQL", 48 ) Else Set colPrinters = objWMIService.ExecQuery( "SELECT * FROM Win32_Printer WHERE DeviceID='" & strPrinter & "'", "WQL", 48 ) End If For Each objItem In colPrinters intStatus = objItem.ExtendedPrinterStatus strPrinter = objItem.DeviceID WScript.Echo "Printer : " & strPrinter WScript.Echo "Print Jobs : " & intJobs WScript.Echo "Status : " & arrStatus( intStatus ) If objItem.ExtendedPrinterStatus <> 8 Then ' Not Paused WScript.Echo "Pause printing . . ." objItem.Pause() blnPaused = True End If Next If blnPaused Then Do Until intStatus = 8 WScript.Echo "Wait . . ." WScript.Sleep 1000 Set colPrinters = objWMIService.ExecQuery( "SELECT * FROM Win32_Printer WHERE DeviceID='" & strPrinter & "'", "WQL", 48 ) For Each objItem In colPrinters intStatus = objItem.ExtendedPrinterStatus WScript.Echo "Status : " & arrStatus( intStatus ) Next Loop End If Set colPrinters = Nothing Set objWMIService = Nothing Sub Syntax Dim strMsg strMsg = vbCrLf _ & "PausePrinting.vbs, Version 1.00" _ & vbCrLf _ & "Pause printing for the specified printer." _ & vbCrLf & vbCrLf _ & "Usage: CSCRIPT PausePrinting.vbs //NoLogo printer" _ & vbCrLf & vbCrLf _ & "Where: ""printer"" is either /D (default printer) or the printer name" _ & vbCrLf _ & " (use doublequotes if the printer name contains spaces)" _ & vbCrLf & vbCrLf _ & "" WScript.Echo strMsg Wscript.Quit 1 End Sub
Δ
[email me]
Δ
Friday, January 6th, 2012
Δ
Get Notified
How to get a notification when machine is online
[download resource files]
Demo
Get notified when a workstation comes back online. Uses ping.exe in a simple loop.
On Error Resume Next strPING = "207.182.153.35" Dim pcEngine CheckEngine( ) Dim WshShell, objExec, input Set WshShell = CreateObject( "WScript.Shell" ) Do While True Set objExec = WshShell.Exec( "ping.exe -n 4 -w 15000 " & strPING ) input = "" Do While True If Not objExec.StdOut.AtEndOfStream Then input = input & objExec.StdOut.Read(1) If InStr( input, "TTL=" ) <> 0 Then Exit Do End If WScript.Sleep 100 Loop If InStr( input, "TTL=" ) <> 0 Then Exit Do Loop MsgBox "[" & Now & "]" & vbCrLf & vbCrLf & strPING & " is now on-line" Do While objExec.Status <> 1 WScript.Sleep 100 Loop Sub CheckEngine pcEngine = LCase( Mid( WScript.FullName, InStrRev( WScript.FullName, "\" ) + 1 ) ) If Not pcEngine = "cscript.exe" Then Set WshShell = CreateObject( "WScript.Shell" ) WshShell.Run "CSCRIPT.EXE //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34) _ & " " & strPING,0,true WScript.Quit(1) End If End Sub
Δ
[email me]
Δ
Tuesday, January 3rd, 2012
Δ
Return User SID
How to return a user SID
[download resource files]
Returns a user sid which can then be used in applying registry hive keys.
' Use custom error handling On Error Resume Next ' Define constants and initialize variables Const wbemFlagReturnImmediately = &h10 Const wbemFlagForwardOnly = &h20 Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 strComputer = "." strUserName = "" strMsg = vbCrLf ' Check "named" command line arguments (command line switches) If WScript.Arguments.Named.Count > 0 Then Syntax( ) End If ' Check "unnamed" command line arguments If WScript.Arguments.Unnamed.Count > 2 Then Syntax( ) Else For numArg = 0 To WScript.Arguments.Unnamed.Count - 1 Step 1 If Left( Wscript.Arguments.Unnamed( numArg ), 2 ) = "\\" Then strComputer = Mid( Wscript.Arguments.Unnamed( numArg ), 3 ) Else strUserName = Wscript.Arguments.Unnamed( numArg ) End If Next End If If WScript.Arguments.Unnamed.Count = 2 Then If strComputer = "." Then Syntax( ) End If End If ' Abort if no user was specified for a remote computer If Not strComputer = "." Then If strUserName = "" Then Syntax( ) End If End If ' Fill in logged on user's name if omitted If strUserName = "" Then Set WshShell = WScript.CreateObject( "WScript.Shell" ) If Err.Number Then ShowError( ) Set WshSysEnv = WshShell.Environment( "PROCESS" ) If Err.Number Then ShowError( ) strUserName = WshSysEnv( "USERNAME" ) End If Set objWMIService = GetObject( "winmgmts://" & strComputer & "/root/CIMV2" ) Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_UserAccount", _ "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly) If Err.Number Then ShowError( ) For Each objItem In colItems If LCase( objItem.Name ) = LCase( strUserName ) Then strMsg = strMsg _ & "Name : " & objItem.Name & vbCrLf _ & "SID : " & objItem.SID End If Next ' Display the result WScript.Echo strMsg Sub ShowError( ) strMsg = vbCrLf & "Error # " & Err.Number & vbCrLf _ & Err.Description & vbCrLf & vbCrLf Syntax( ) End Sub Sub Syntax( ) strMsg = strMsg & vbCrLf _ & "GetSID.vbs, Version 1.00" & vbCrLf _ & "Retrieve Security ID for the specified user on any computer." & vbCrLf & vbCrLf _ & "Usage: [ CSCRIPT ] GETSID.VBS [ username [ \\computername ] ]" & vbCrLf & vbCrLf _ & "Where: " & Chr(34) & "username" & Chr(34) & " is the optional user name (mandatory if computername" & vbCrLf _ & " is specified; default is the logged on user name)" & vbCrLf _ & " " & Chr(34) & "computername" & Chr(34) & " is the optional name of a remote computer (default" & vbCrLf _ & " is the local computer name)" & vbCrLf _ & vbCrLf _ & "" & vbCrLf _ & "" WScript.Echo strMsg WScript.Quit(1) End Sub
Δ
[email me]
About
I'm a Computer
Systems Engineer
Living and Loving Life
Author