5 Useful VB Windows Scripts to Automate Your Computer Use
Pinterest Whatsapp
Advertisement

Whether you’re an IT analyst or a regular computer user, there are a lot of tasks you may need to do frequently on your PC. VB Scripts are scaled down Visual Basic programs that serve as Windows scripts that can do anything from pull up important information about your computer hardware, to stopping and starting services or resetting your network card.

It’s possible to learn how to do all of those individual things the normal way, or do them using batch files. But VB scripts are better than batch scripts Better Than Batch: A Windows Scripting Host Tutorial Better Than Batch: A Windows Scripting Host Tutorial Read More because they’re more flexible. If you store the following scripts in a common place that’s quick to get to when you need it, you can accomplish these tasks in a fraction of the time. You just double-click the script, answer a prompt, and the task is done.

Take a look at the following VB Windows scripts and if you see any you’d like to use, just copy and paste the script into Notepad or other coding notes tool 7 Best Note-Taking Tools for Programmers 7 Best Note-Taking Tools for Programmers Good note-taking skills are key to staying organized as a programmer. Here are the best note-taking apps designed with coders and developers in mind. Read More and save it as a WSF file.

Prepare Your Windows Scripts

Each of the scripts detailed below will run with just a double click so long as you’ve named the file with the .WSF extension, and you’ve also enclosed the code at the beginning with:

<job>
<script language="VBScript">

And close out the code with:

WScript.Quit
</script>
</job>

This ensures that Windows will recognize the language your script is written in, and process it properly.

1. Use Windows Scripts for Computer Information

Windows offers something called WMI, or Windows Management Instrumentation, which provides your script with an interface to access components of the operating system. You can actually run queries against WMI to get current live information about your system. Microsoft offers a full list of all of the categories of queries you can make against the system.

We’ve covered how to use VBA to pull computer information into Excel How to See All Your PC Information Using a Simple Excel VBA Script How to See All Your PC Information Using a Simple Excel VBA Script Excel and 10 minutes of work will give you more detailed information about your computer than you ever thought possible. Sounds too good to be true? That's Windows, if you know how to use it. Read More , but you can do this same thing using a simple VB script outside of Excel.

In this example we’re going to query the system for processor information (family, manufacturer, and number of cores), battery information How to Save Battery Life in Windows 10 With Power Throttling How to Save Battery Life in Windows 10 With Power Throttling Microsoft introduced power throttling which gives Windows users more control over how individual apps handle battery consumption while running in the background. Read More (description and status), and logical disk information How to Save Disk Space in Windows 10 How to Save Disk Space in Windows 10 In terms of disk space requirements, Windows 10 is downright gluttonous. Wasting 20 GB on a small SSD can be frustrating. Fortunately, you can reduce the Windows 10 footprint and reclaim some of that space. Read More (name, free space remaining, and overall size). Then we’ll output all of this information to a CSV file for easy viewing.

The first step is to set up the FileSystemObject you’ll use to output to the CSV file, and create the file:

Set oFSO = CreateObject("Scripting.FileSystemObject")
sFile1 = "MyComputerInfo.csv"
Set oFile1 = oFSO.CreateTextFile(sFile1, 1)

The next step is to set up the WMI query and execute it:

strQuery = "SELECT Family,Manufacturer,NumberOfCores FROM Win32_Processor"
Set colResults = GetObject("winmgmts://./root/cimv2").ExecQuery( strQuery )

Finally, sort through the results and output the information to the CSV file. If you want to be fancy, preface this with a couple of lines to help make your output file look better:

oFile1.WriteLine "Processor Information"
oFile1.WriteLine "------"

For Each objResult In colResults
  strResults = "Family:,"+CStr(objResult.Family)
  oFile1.WriteLine strResults
  strResults = "Manufacturer:,"+CStr(objResult.Manufacturer)
  oFile1.WriteLine strResults
  strResults = "Number of Cores:,"+CStr(objResult.NumberOfCores)
  oFile1.WriteLine strResults
Next

If you run your code now, this is what your output will look like:

windows script computer information

For the next two sections of your code, you’re just going to repeat and change the query to look for the additional information. Here’s the battery info query:

oFile1.WriteLine ""
strQuery = "SELECT Description,Status FROM Win32_Battery"
Set colResults = GetObject("winmgmts://./root/cimv2").ExecQuery( strQuery )
oFile1.WriteLine "Battery Information"
oFile1.WriteLine "------"

For Each objResult In colResults
  strResults = "Status:,"+CStr(objResult.Description)
  oFile1.WriteLine strResults
  strResults = "Description:,"+CStr(objResult.Status)
  oFile1.WriteLine strResults
Next

And here’s the next section for the logical disk query:

oFile1.WriteLine ""
strQuery = "Select Name, FreeSpace, Size from Win32_LogicalDisk"
Set colResults = GetObject("winmgmts://./root/cimv2").ExecQuery( strQuery )
oFile1.WriteLine "Disk Information"
oFile1.WriteLine "------"

'Identify the Logical Disk Space
For Each objResult In colResults
  strResults = "Name:,"+CStr(objResult.Name)
  oFile1.WriteLine strResults
  strResults = "Free Space:,"+CStr(objResult.FreeSpace)
  oFile1.WriteLine strResults
  strResults = "Disk Size:,"+CStr(objResult.Size)
  oFile1.WriteLine strResults
Next

Finally, remember to close out the code by closing the file and setting the objects to “Nothing”:

oFile1.Close

Set oFile1 = Nothing
set colResults = Nothing
strResults = ""

Put all that code into your new .WSF file, run it, and here’s what your output will look like:

5 Useful VB Windows Scripts to Automate Your Computer Use computer info2

Just swap up the queries above for any other computer devices or software you want to get information about, and you can get a full system report How To Create An Automated PC Health Reporting System How To Create An Automated PC Health Reporting System You're out having lunch as your mobile alerts you to an important text. The SMS reads: "Home Computer Alert: 3 hacking attempts." This is not fiction! Let us show you how to do this! Read More any time you like with just a click of the mouse.

2. Stop and Start Services

There will be times when certain services have issues, and require just a quick restart to get running properly again. This is especially true in IT Before You Study IT, Know What You're Getting Into Before You Study IT, Know What You're Getting Into Information Technology (IT) has become such a widespread career choice. But few people actually know what IT is and what its discipline entails. Read More when you’re forced to run server software that is sometimes a little bit buggy.

If you want to shave a minute or so off of the service restart process, just store the following script some place convenient. It’ll prompt you to type in the name of the service you want to restart, and then it’ll do exactly that.

Since stopping and starting services requires administrative privileges, you need to place the following code at the start of your script to give your script elevated privileges:

If Not WScript.Arguments.Named.Exists("elevate") Then
  CreateObject("Shell.Application").ShellExecute WScript.FullName _
  , """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
  WScript.Quit
End If

Once this is done, add the rest of the code to run the input box for user input, launch the command window, and send it the “net stop” and “net start commands”:

Set cmdShell = CreateObject("WScript.Shell")
strServiceName=Inputbox("Inter Service to Stop","Input Required")
cmdShell.Run "cmd.exe"
WScript.Sleep 1000

cmdShell.SendKeys "net stop "+strServiceName
cmdShell.SendKeys "{Enter}"
WScript.Sleep 1000

cmdShell.SendKeys "net start "+strServiceName
cmdShell.SendKeys "{Enter}"
WScript.Sleep 1000

cmdShell.SendKeys "Exit"
cmdShell.SendKeys "{Enter}"

That’s all there is to it. No need to hunt around for the services tool. Just run this script and stop and start any service in seconds.

3. Change Registry Settings, Default Admin Password

With the following script, we’re going to kill two birds with one stone. This script will show you how to edit the registry 5 Windows 10 Registry Tweaks to Improve & Unlock Features 5 Windows 10 Registry Tweaks to Improve & Unlock Features The registry editor is the only way to enable some of Windows 10's hidden features. Here we'll show you easy tweaks like enabling the dark theme or hiding folders. Read More with a VB script. It’ll also give you a script that’ll let you set the default Windows username and password by editing those registry settings.

Here’s how it works. First, since editing the registry requires admin rights, you’ll need to set up elevated privileges for your script:

If Not WScript.Arguments.Named.Exists("elevate") Then
  CreateObject("Shell.Application").ShellExecute WScript.FullName _
  , """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
  WScript.Quit
End If

First run two input boxes to ask the user what user name and password to use:

strUserName=Inputbox("Enter the default User Name","Input Required")
strPassword=Inputbox("Enter the default Password","Input Required")

Next, set up the shell object, and write those values to the appropriate registry keys:

Set wshShell = CreateObject( "WScript.Shell" )
wshShell.RegWrite "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultUserName", strUserName, "REG_SZ"
wshShell.RegWrite "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultPassword", strPassword, "REG_SZ"
Set wshShell = Nothing

And that’s all there is to it. The “RegWrite” method lets you write any value to any registry key using a VB Windows script. All you have to know is the appropriate path.

Run the script and answer the prompts.

5 Useful VB Windows Scripts to Automate Your Computer Use password prompt

The values you enter will get inserted right into the registry settings you’ve set up in the script.

5 Useful VB Windows Scripts to Automate Your Computer Use registry entries

Play around with the script and tweak it to your liking. You can edit any registry keys you like, so be creative!

4. Reset Your Network Connection

Resetting your network connection using VB scripting How To Write A Windows Script To Change Network Settings On The Fly How To Write A Windows Script To Change Network Settings On The Fly In many offices or work environments, you might need to redefine your network settings to connect to different networks. I found myself in this situation often enough, and got so tired of browsing to the... Read More is something we’ve covered before here at MakeUseOf. The following version of this is actually scaled down and much simpler to implement. Instead of prompting for individual network cards, it resets all of your active connections which would hopefully resolve any network issues you may be having.

As with other scripts that need admin rights, you’ll need to add the section at the start for elevated privileges. Copy that code from the script above.

Next, create the WMI object and query it for a list of enabled network adapters on your system:

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
  "SELECT * FROM Win32_NetworkAdapter Where NetEnabled = 'True'")

Finally, loop through all of the enabled adapters and reset them:

For Each objItem in colItems
  objItem.Disable
  WScript.Sleep 1000
  objItem.Enable
Next

This will reset all of your active network adapters 8 CMD Commands to Manage (Wireless) Networks in Windows 8 CMD Commands to Manage (Wireless) Networks in Windows If you want full and absolute control over your network, then you'll have to start using Command Prompt. Here are the most useful commands for managing and troubleshooting your home network. Read More , which is often the fastest way to resolve annoying network issues. Keep this script handy and try it first any time you have a slow network or other weird network problems.

5. Ping Devices or Websites

I’ve saved my favorite VB windows script for last. This is one that I actually set up as a scheduled task on my home computer and have it run several times a day just to check if my website is active 3 Ways To Figure Out If Your Favorite Website Is Down 3 Ways To Figure Out If Your Favorite Website Is Down There are a few websites out there that are devoted simply to answering the basic question that you'll eventually ask: "Is this website down?" Here, we have three of these websites, and they are all... Read More . I have the script email me if the site is down. You can use this same script to monitor important servers or computers on your network and email yourself any time your script can’t ping the device.

First, set up the script for the target you want to ping, create the shell object, and then run the ping command.

strTarget = "topsecretwriters.com"
Set WshShell = WScript.CreateObject("WScript.Shell")
Ping = WshShell.Run("ping -n 1 " & strTarget, 0, True)

Use a Select Case statement to run through the Ping results and respond accordingly. If results come back as zero, then you know the site (or server) is online and you don’t have to do anything. If it returns a “1” then the ping failed and you need to do something. In my case, I send an email using the Windows CDO object:

Select Case Ping
  Case 0
  Case 1
    Set objMessage = CreateObject("CDO.Message")
    Set objConfig = CreateObject("CDO.Configuration")
    objConfig.Load -1
    Set Flds = objConfig.Fields
    With Flds
      .Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
      .Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
      .Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="xxxxxx@gmail.com"
      .Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="xxxxxxxxxxxxxxxxx"
      .Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.gmail.com"
      .Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
      .Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=465
      .Update
    End With
    With objMessage
      Set .Configuration = objConfig
      .Subject = "Your site is offline"
      .From = "me@mycomputer.com"
      .To = "xxxxxx@gmail.com"
      .TextBody = "Hey, your website is offline."
      .Send
    End With
End Select

Once the script runs and can’t ping the device or website, you get an instant message.

5 Useful VB Windows Scripts to Automate Your Computer Use site offline

It’s quick and easy, and every efficient!

Using VB Windows Scripts to Control Your Computer

These are just a few examples of some of the cool things you can do with VB scripting to streamline your computer use. There are lots of other things you can do like automated backups with VB and Synctoy How To Create A Data Backup Tool With SyncToy & VB Script How To Create A Data Backup Tool With SyncToy & VB Script We've covered a lot of backup solutions here at MUO, and all of these solutions are great, but if you're working in an environment that is wary about free 3rd party software packages, or companies... Read More , automating telnet commands How to Automate Telnet Commands Using VB Script How to Automate Telnet Commands Using VB Script Writing batch jobs and more recently Windows scripts is an activity that really makes up the bulk of how the large majority of network and system administrators do their jobs faster, and simplify what would... Read More , or even open and control application windows 3 Ways To Open Applications & Windows Maximized With VB Script [Windows] 3 Ways To Open Applications & Windows Maximized With VB Script [Windows] If there is one thing I love to do, it's write VB scripts. Whether it's a Windows Script file or a VBA script inside an application, scripting provides the ability to add functionality to applications... Read More .

What are some of the things you’ve automated on your computer with a Windows script? Do you write yours using VB, or use some other tool like PowerShell Powershell Cmdlets That'll Improve Your Windows Admin Skills Powershell Cmdlets That'll Improve Your Windows Admin Skills Powershell is equal parts command line tool and scripting language. It gives you the ability to automate your computer via the same commands you use to administer it. Read More ?

Explore more about: Computer Automation, Scripting.

Enjoyed this article? Stay informed by joining our newsletter!

Enter your Email

Leave a Reply

Your email address will not be published. Required fields are marked *