Pages

Wednesday, December 17, 2008

Windows Script Files (WSF) & Objects in Windows Scripting Host

Using Windows Script Files (.wsf)

While using JavaScript and VBScript and their respective files (.js and .vbs), a need arises for a more structured approach and broader functionality. I would like to encapsulate certain behavior into classes in order to avoid copying and pasting code into new script files. For example, I want to completely stop, and later start, certain functionality in the operating system. Let's say there are VMWare Server services running, there may be tray icon and other programs loaded into memory and we want to get rid of them to free resources to play a game or do something else. The way to stop all the services and close open programs is to use Windows Scripting Host and run a script that does it.
Stopping services involves a bit of work in querying the system for the list, enumerating the list and stopping the service, etc. Too much code in every file. The functionality of searching for the service and doing whatever is necessary to stop it could be encapsulated into one function call - a method - called stopService(). There could be a stopProgram() as well. These, then, could be a part of a class that encapsulate the behavior. This class could be used from all the scripts - one that starts/stops the antivirus, another that operates virtual environments, yet another that sets up internet session, etc. These separate scripts need to include the behavior of the class that starts and stops the programs and services.

This is where Windows Script Files come into play. Files with extension .wsf are executed by the Windows Scripting Host (WSH) just like .js and .vbs files. More than one scripting language can be used in a file as opposed to .js and .vbs, which contain only one language. An example of a WSF would be:

<job id="IncludeExample">
<script language="JScript" src="FSO.JS"/>
<script language="VBScript">
' Get the free space for drive C.
s = GetFreeSpace("c:")
WScript.Echo s
</script>
</job>

You can see it is using VBScript to call a function in an external file fso.js. This solves the "include" issue. The good thing is that WSH supports classes so a class can be declared as







Class SomeClass

public sub hi
WScript.Echo "hi"
end sub

End Class






and saved in SomeClass.vbs. Then, the run.wsf file could look like the following:





<job id="IncludeExample">


   <script language="VBScript" src="someClass.vbs" />


  
   <script language="VBScript">


      dim a


      set a = New SomeClass


     
      a.hi


   </script>


</job>








No comments: