How to call a .Net DLL form a VBScript

You might be wondering how do you call a .Net DLL from a VB Script, well look no further as I will explain to you steps by step how do you achieve on doing this.

You might be wondering why do you want to do this?

Why not just do everything on .Net or VBScript?

Well there might be some instances this will be useful, like modifying a start-up script for GPO which is already in VBScript but you want to extend it safely (compiled codes) or just reusing available DLL’s that are out there in your organization saving you time to redevelop the same thing again. There are a lot of reasons that you want to do this but this is why I am doing it, unless someone else suggest of a better way of doing it anyways I am writing this so that if anyone needed this reference its just here.

Ok lets start with what you need. Definitely you need to develop or use a existing DLL, for this example we will develop from scratch, you also need the VBScript that you want to edit or create and that’s it.

Step 1: Your DLL. Fire up Visual Studio you can develop either in C#, VB or any language you want, this sample will be C#. You need to create a Class Library Project.

using System;
using System.Runtime.InteropServices;
namespace MyDLL
{
 [ComVisible(true)]
 public class Operations
 {
 [ComVisible(true)]
 public string getValue1(string sParameter)
 {
 switch (sParameter)
 {
 case "a":
 return "A was chosen";

 case "b":
 return "B was chosen";

 case "c":
 return "C was chosen";

 default:
 return "Other";
 }
 }
 public string getValue2()
 {
 return "From VBS String Function";
 }
 }
}

On the code above applying the ComVisibleAttribute Class controls accessibility of an individual managed type or member, or of all types within an assembly, to COM. You can apply this attribute to classes, structures, interfaces, delegates, enumerations, fields, methods, assemblies or properties. By default it is set to true but for in case you want to hide the individual type you can just set it to false (I just showed it for reference purposes, as you notice the getValue2 does not that attribute but still is still visible).

Build the project.

Step 2: Register your assembly / DLL

Now after creating this Class Library Project you have to configure it so that when you compile it will register on the system assembly. There are two ways of registering an assembly first is via command prompt. If you have .NET Framework 2.0 installed, regasm would be in following path at

C:\windows\microsoft.net\Framework\v2.0.50727\regasm.exe

And use the following for registering and unregistering an assembly

register assembly manually

The one on top

regasm /codebase c:\YourClass.dll

registers it and the one on the bottom

regasm /u c:\YourClass.dll

unregisters it. Now what that the /codebase option stand for?
You need to use the /codebase switch when you don’t have your assembly in GAC because that will add absolute path for your assembly in registry so that COM client can find it.

Another option is Directly to Visual Studio, this is the easy way and it’s as easy as ticking a check box in the project properties

register assembly

Now you have your DLL ready.

Step 3: Create your VBScript and here is my sample

dim myObj
Dim myClass
Set myObj = CreateObject("MyDLL.Operations")
MsgBox myObj.getValue1("a”)
MsgBox myObj.getValue2()

Now run your VBScript and that’s it.

List the IIS Versions of your Webserver

This is in line with my post here as I am doing the Application Architecture Landscape for our Enterprise Architecture.  At one point I need to check what versions of IIS we are running in each server, so once again the easiest way for me is to just write a VBS Script to handle that.  Here is how it goes

Set oExcel = CreateObject("Excel.Application")If (Err.Number <> 0) Then
 On Error GoTo 0
 Wscript.Echo "You need to install an Excel Application"
 Wscript.Quit
End If
On Error GoTo 0

sExcelPath = "D:\Servers-STJOHN.xls"

' Open Spreadsheet and Use First Worksheet.
oExcel.WorkBooks.Open sExcelPath
Set objSheet = oExcel.ActiveWorkbook.Worksheets(1)

' Loop through all the items in Speadsheet, 1st row is a Header Row
intRow = 2
Do While objSheet.Cells(intRow, 1).Value <> ""
 strServerName = objSheet.Cells(intRow, 1).Value
 On Error Resume Next
 ' This takes care if you dont have IIS installed on the server

 'Get the IIS Server Object
 Set objWMIService = GetObject("winmgmts:{authenticationLevel=pktPrivacy}\\" & strServerName & "\root\microsoftiisv2")
 If (Err <> 0) Then

 Else

 Set colItems = objWMIService.ExecQuery("Select * from IIsWebInfo")

 For Each objItem in colItems
 'Wscript.Echo "Major IIS Version Number: "  objItem.MajorIIsVersionNumber
 'Wscript.Echo "Minor IIS Version Number: "  objItem.MinorIIsVersionNumber
 'Wscript.Echo "Name: " & objItem.Name
 Set oFile = CreateObject("Scripting.FileSystemObject")
 Set oTextFile = oFile.OpenTextFile("D:\IIS-Versions.txt", 8, True)
 oTextFile.WriteLine(strServerName & " - " & objItem.MajorIIsVersionNumber & "." & objItem.MinorIIsVersionNumber & " - " & objItem.Name)
 oTextFile.Close

 Set oTextFile = Nothing
 Set oFile = Nothing
 Next

 End If
 intRow = intRow + 1
Loop

' Close Workbook and Excel.
oExcel.ActiveWorkbook.Close
oExcel.Application.Quit

' Clean up.
Set oExcel = Nothing
Set objSheet = Nothing
Set objUser = Nothing
Set oW3SVC = Nothing
Set oWebSite = Nothing
Wscript.Echo "Done"

Note : This is taking into consideration that you already know what are your servers and listed it on an Excel Spreadsheet

List all Computers in a Domain the quick way!

This in in conjunction with my work here where I need to list all websites in a server, now I need to list all servers and whats the quick way of doing it? Again scripting in VBS.

Here is how I’ve done

const oFileName ="AllComputers.csv"
set oCmd = createobject("ADODB.Command")
set oConn = createobject("ADODB.Connection")
set oRS = createobject("ADODB.Recordset")

oConn.open "Provider=ADsDSOObject;"
oCmd.ActiveConnection = oConn

set oRoot = GetObject("LDAP://RootDSE")

oCmd.CommandText = "<LDAP://" & oRoot.Get("defaultNamingContext")  & ">;(objectCategory=Computer);" & _
          "name, distinguishedName, operatingsystem, operatingsystemservicepack, operatingsystemversion;subtree"
oCmd.Properties("page size")=1000

set oRS = oCmd.Execute
set oFSO = CreateObject("Scripting.FileSystemObject")
set oCSV = oFSO.CreateTextFile(oFileName)

sQuotations = """"

while oRS.EOF <> true and oRS.BOF <> true
    oCSV.writeline(sQuotations & oRS("name") & sQuotations & "," & _
    sQuotations & oRS("distinguishedName") & sQuotations & "," &  _
    sQuotations & oRS("operatingsystem") & sQuotations & "," & _
    sQuotations & oRS("operatingsystemservicepack") & sQuotations & "," & _
    sQuotations & oRS("operatingsystemversion") & sQuotations)
    oRS.MoveNext
wend

oCSV.Close
oConn.close

wscript.echo "Done!"

How to List all Websites in IIS

Its been a while since I had posted something that is because my Laptop gave up on me.  Anyways I’m back in action but still no laptop…  Anyways I was tasked to get to list all websites that we had on the organization as we are implementing an Enterprise Architecture tool which need to be populated (the EA tool is called Troux).  Now my dilemma is that I dont have anything on the desktop I have now, just a standard installation of OS and thats it so whats the best way to achieve the solution?

Aha!!!! Use the old school style vbs scripting.

So how do I achieve that? First is that you should know what are your servers and list them on a spreadsheet, In my case its good as we have it already pre-populated on the EA tool that we have so Ill just export it.  So I have to create a code that will loop though that Spreadsheet and check what Websites are in there.  Here is how I do it.

Set oExcel = CreateObject("Excel.Application")
If (Err.Number <> 0) Then
 On Error GoTo 0
 Wscript.Echo "You need to install an Excel Application"
 Wscript.Quit
End If
On Error GoTo 0

sExcelPath = "C:\Scripts\SERVERS-new.xls"

' Open Spreadsheet and Use First Worksheet.
oExcel.WorkBooks.Open sExcelPath
Set objSheet = oExcel.ActiveWorkbook.Worksheets(1)

' Loop through all the items in Speadsheet, 1st row is a Header Row
intRow = 2
Do While objSheet.Cells(intRow, 1).Value <> ""
 strServerName = objSheet.Cells(intRow, 1).Value
 On Error Resume Next
 ' This takes care if you dont have IIS installed on the server
 
 Dim oW3SVC, oWebSite

 'Get the IIS Server Object 
 Set oW3SVC = GetObject("IIS://" & strServerName & "/W3SVC")
 If (Err <> 0) Then
 
 Else
 For Each oWebSite In oW3SVC
 If oWebSite.class = "IIsWebServer" Then

 Set oFile = CreateObject("Scripting.FileSystemObject")
 Set oTextFile = oFile.OpenTextFile("C:\Scripts\IIS.txt", 8, True)
 'Get the Name of the Website
 oTextFile.WriteLine(strServerName & "," & oWebSite.ServerComment)
 oTextFile.Close
 
 Set oTextFile = Nothing
 Set oFile = Nothing


 End If
 Next
 End If
 intRow = intRow + 1
Loop

' Close Workbook and Excel.
oExcel.ActiveWorkbook.Close
oExcel.Application.Quit

' Clean up.
Set oExcel = Nothing
Set objSheet = Nothing
Set objUser = Nothing
Set oW3SVC = Nothing
Set oWebSite = Nothing
Wscript.Echo "Done"

Save it as [Filename].vbs and click the File then get your results. Simple yet effective specially when you have more than 200 websites on your organization, it saves your time jotting them down and you dont know you might discover new websites.

Follow

Get every new post delivered to your Inbox.

Join 774 other followers