This document contains code for an assignment on scripting and automation. It includes VBScript code written in an HTA (HTML Application) format. The code queries WMI to retrieve information about network shares, printers, users, scheduled tasks and more. It populates this information onto HTML tabs for display. The code includes functions for formatting dates/times and managing the UI elements and tab display.
This document contains code for an assignment on scripting and automation. It includes VBScript code written in an HTA (HTML Application) format. The code queries WMI to retrieve information about network shares, printers, users, scheduled tasks and more. It populates this information onto HTML tabs for display. The code includes functions for formatting dates/times and managing the UI elements and tab display.
Drepturi de autor:
Attribution Non-Commercial (BY-NC)
Formate disponibile
Descărcați ca TXT, PDF, TXT sau citiți online pe Scribd
This document contains code for an assignment on scripting and automation. It includes VBScript code written in an HTA (HTML Application) format. The code queries WMI to retrieve information about network shares, printers, users, scheduled tasks and more. It populates this information onto HTML tabs for display. The code includes functions for formatting dates/times and managing the UI elements and tab display.
Drepturi de autor:
Attribution Non-Commercial (BY-NC)
Formate disponibile
Descărcați ca TXT, PDF, TXT sau citiți online pe Scribd
' Assignment 1 for Advanced Application Group (Scripting)
' ICAB4220A - Create Scripts for Networking ' ICAB4225A - Automate Processes ' Written by Paul Willes ' Due Date Tuesday 14th November 2007 ' This code has been written in HTA, which is HTML Application ' An HTA runs as a fully trusted application and therefore has more privileges t han a regular HTML file. '(http://en.wikipedia.org/wiki/HTA_%28programming_language%29) ' This allows us to use HTML (and DHTML) elements for the user interface and sti ll access the WMI elements ' Assignment1.vbs is not run directly, but is run using Assignment1.hta ' There are 4 files in this assignment. ' - Assignment1.hta - The HTML document which contains all t he HTML elements - ' This is the file that is doublec licked to start. ' - Assignment1.css - Contains all the cascading style sheet information (gives the html it's style) ' - Assignment1_UI.vbs - vbscripts that turn the HTML into DHTML - Dyna mic HTML ' - Assignment1.vbs - vbscripts that do the work to answer t he assignment 1 tasks 'Header Option Explicit ' Forces us to declare all the variables to avoi d misspellings of variable names On Error Resume Next ' Error handling - goes to the next statement if a statm ent fails 'Common Variables - to avoid declaring them every time Dim objWMIService ' A link to the Windows Management Interface Ser vice Dim objApplication ' A link to the Application object Dim objFSO ' A link to the File System Object Dim objShell ' A pointer to the wScript Shell object Dim objNetwork ' A pointer to the wScript Network object Dim LastTimeWritten ' A string that contains the date that the Appli cation Event Log was last written to Dim objPrinterRecordSet ' A record set that contains servers that have printer q ueues and printer information Dim objOURecordSet ' A record set that contains OU information Dim objUserRecordSet ' A record set that contains User information Dim EventLogSize ' The number of entries in the event log since this program was started Const EVENT_SUCCESS = 0 Const EVENT_FAILED = 2 '=============================================================================== ====================== '=============================================================================== ====================== '==== Window_OnLoad '==== Purpose: When the HTA loads, this is the code that is run first '==== Inputs: None '==== Returns: The following common variables are assigned '==== objWMIService '==== objApplication '==== objFSO '==== objShell '==== The HTML elements are arranged to form tab buttons and t abs '==== Information on the tabs are updated '=============================================================================== ====================== '=============================================================================== ====================== Sub Window_OnLoad ' Header Dim strComputer Dim wmiNS Dim wmiRoot ' Assign values to some variables that are common to some Questions strComputer = "." 'This computer wmiNS = "\root\cimv2" 'WMI Namespace wmiRoot = "winmgmts:{impersonationLevel=impersonate}!\\" &_ strComputer & wmiNS ' Create a link to the Windows Management Interface Service Set objWMIService = GetObject(wmiRoot) ' Create a link to the application object Set objApplication = CreateObject("Shell.Application") ' Create a link to the File System Object Set objFSO = CreateObject("Scripting.FileSystemObject") ' Create a link to the wScript Shell Set objShell = CreateObject("Wscript.Shell") ' Create a link to the wScript Network object Set objNetwork = CreateObject("WScript.Network") ClearInitLog ' Make sure that the information on the Tabs is up to date EventLogSize = 0 ' Initially there are no entries in the event lo g since the program was started LastTimeWritten = YEAR(Date()) & Pd(Month(date()),2) & Pd(DAY(date()),2) &_ Pd(Hour(time()),2) & Pd(Minute(time()),2) & Pd(Second(time()),2) &_ ".000000" & fnCurrentTimeZone() Question1Refresh ' Populates the list of network shares onto TabQ 1 Question2Refresh ' Populates the list of network adaptors and the ir properties onto TabQ2 Question3Refresh ' Puts information about the current domain or w orkgroup onto TabQ3 Question4Refresh ' Places list of OUs and Users onto TabQ4 Question5Refresh ' Places list of scheduled tasks onto TabQ5 Q5cRefreshLocalPrinters Q6bListLocalGroups ' Puts the list of local groups onto TabQ6 UpdateEventLog ' Place all the tab buttons and tabs in the correct position for the user Interf ace (Located in Assignment1_UI.vbs) LOAD_UI End Sub 'Window_OnLoad '=============================================================================== ====================== '=============================================================================== ====================== '==== pd '==== Purpose: creates a string that is a number with zeros at the fron t to make the required number of digits '==== Inputs: n The number we want in our string '==== totalDigits The number of digits in our string '==== Returns: A string with leading zeros to make up the required numb er of digits '=============================================================================== ====================== '=============================================================================== ====================== Function pd(n, totalDigits) if totalDigits > len(n) then pd = String(totalDigits-len(n),"0") & n else pd = n end if End Function '=============================================================================== ====================== '=============================================================================== ====================== '==== fnCurrentTimeZone '==== Purpose: creates a string that is "(+-)OOO" is the current bias f or local time translation '==== Multiply the number of hours that your time zone is ahea d or behind GMT by 60 '==== Add an additional 60 if your time zone is using daylight savings time '==== Inputs: n The number we want in our string '==== totalDigits The number of digits in our string '==== Returns: A string with leading zeros to make up the required numb er of digits '=============================================================================== ====================== '=============================================================================== ====================== Function fnCurrentTimeZone() ' Header Section Dim ColItems Dim objItem Dim intCurrentTimeZone ' Get a collection of computer systems from the Win32_ComputerSystem object in t he WMI service Set colItems = objWMIService.ExecQuery _ ("SELECT * FROM Win32_ComputerSystem") ' Cycle through the list of computer systems For Each objItem In colItems ' Get the current time zone intCurrentTimeZone = objItem.CurrentTimeZone Next 'objItem ' Pad the current time zone to 3 digits with a leading + or - If intCurrentTimeZone < 0 Then fnCurrentTimeZone = "-" & Pd(-intCurrentTimeZone,3) Else fnCurrentTimeZone = "+" & Pd(intCurrentTimeZone,3) End If End Function '=============================================================================== ====================== '=============================================================================== ====================== '==== Question1Refresh '==== Purpose: To put the list of network shares onto TabQ1 '==== Inputs: None '==== Returns: List of the names of the Network shares into SelectNetwo rkShares on TabQ1 '==== Clears the Folder name, the share name and the share des cription fields on TabQ1 '==== Pseudo code '==== Clear any information out of SelectNetworkShares '==== Query WMI to get a collection of network share names '==== Make SelectNetworkShares big enough to display all network share s '==== Cycle through all the network share names and place the names in to SelectNetworkShares '==== Clear the Folder name, the share name and the share description fields on TabQ1 '==== Free any memory used by variables '=============================================================================== ====================== '=============================================================================== ====================== Sub Question1Refresh ' Header Section Dim colShares ' Collection of Shares Dim objShare ' An instance of a share Dim objOption ' An element to be added to SelectNetworkShares ' which contains the name of one network share ' Clear any information out of SelectNetworkShares For Each objOption in SelectNetworkShares.options objOption.RemoveNode Next 'objOption ' Query WMI to get a collection of network share names Set colShares = objWMIService.ExecQuery("Select Name from Win32_Share") ' Make SelectNetworkShares big enough to display all network shares SelectNetworkShares.size = colShares.count ' Cycle through all the network share names and place the names into SelectNetwo rkShares For each objShare in colShares ' A Select element in HTML is made up of a collection of Option elements ' An option element has a number of attributes. We will use two of the attributes - Text and Value ' The Text attribute is what will be displayed, while the Value attribute is the part that is used ' to process what is to be done set objOption = document.createElement("option") objOption.text = objShare.Name objOption.value = objShare.Name ' Adds the Option element into SelectNetworkShares SelectNetworkShares.add(objOption) ' Debug AddToInitLog "Q1_Shares: "& objShare.Name Next 'objShare ' Clear the Folder name, the share name and the share description fields on TabQ 1 txtQ1aFolderName.value = "" txtQ1aShareName.value = "" txtQ1aShareDescription.value = "" ' Free any memory used by variables Set colShares = Nothing End Sub 'Question1Refresh '=============================================================================== ====================== '=============================================================================== ====================== '==== Q1aSelectFolder '==== Purpose: To use the shell application "BrowseForFolder" to select a folder '==== Inputs: User interaction to select the folder '==== Returns: The folder name selected is placed into txtQ1aFolderName on TabQ1 '==== Pseudo code '==== Run the BrowseForFolder application '==== If a folder was selected then place the name of the folder into txtQ1aFolderName '==== Free any memory used by variables '=============================================================================== ====================== '=============================================================================== ====================== Sub Q1aSelectFolder 'Header Section dim objFolder ' A pointer to the folder that is chosen by the BrowseForFolder method dim ulFlags ' Flags used by BrowseForFolder Const BIF_RETURNONLYFSDIRS = 1 ' Return only File syatem directories Const BIF_EDITBOX = 16 ' Place an editbox into the form so that the use r can type a filename const ssfDESKTOP = 0 ' Microsoft Windows Desktop virtual folder that is the root of the namespace 'Reference Section ulFlags = BIF_EDITBOX or BIF_RETURNONLYFSDIRS ' Combine the flags ' Run the BrowseForFolder application set objFolder = objApplication.BrowseForFolder(0, _ "Select a folder to share", ulFlags, ssfDESKTOP) ' If a folder was selected then place the name of the folder into txtQ1aFolderNa me if not (objFolder is nothing) then txtQ1aFolderName.Value = objFolder.self.path end if 'not (objFolder is nothing) ' Free any memory used by variables set objFolder = nothing ' Set to Nothing to free memory End Sub 'Q1aSelectFolder '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 1 a) Creating a Network Share (including the ability to che ck to see if a folder exists) '==== Purpose: To create a network share '==== Inputs: txtQ1aFolderName, txtQ1aShareName, txtQ1aShareDescription '==== Returns: Creates a network share '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that Folder Name is not blank '==== Check that the folder exists '==== Check that Share Name is not blank '==== Check that Share Name does not exist '==== Create a link to the Win32_Share object '==== Share the folder with the network '==== Free any memory used by variables '==== Place an entry in the applications event log '==== Update TabQ1 to show the shares ''============================================================================== ======================= '=============================================================================== ====================== Sub Q1aShareFolder ' Header Section Const FILE_SHARE = 0 Const MAXIMUM_CONNECTIONS = 25 Dim colShares ' Collection of shares o n the computer Dim objNewShare ' Link to the service th at creates a new share Dim errReturn ' Error returned by func tion Dim strFolderName ' Folder name that is to be created Dim strShareName ' Share name that is to be created Dim strShareDesc ' Share description that is to be created ' Reference Section strFolderName = txtQ1aFolderName.value strShareName = txtQ1aShareName.value strShareDesc = txtQ1aShareDescription.value ' Check that Folder Name is not blank If strFolderName = "" Then msgbox("Enter a folder name") errReturn = -1 ' Check that the folder exists ElseIf Not objFSO.FolderExists(strFolderName) Then msgbox("Folder " & strFolderName & " does not exist") errReturn = -2 ' Check that Share Name is not blank ElseIf strShareName = "" Then msgbox("Enter a share name") errReturn = -3 Else 'strFolderName <> "" and objFSO.FolderExists(strFolderName) and str ShareName <> "" ' Check that Share Name does not exist Set colShares = objWMIService.ExecQuery _ ("Select Name from Win32_Share " &_ "WHERE Name = '" & strShareName & "'") If colShares.Count > 0 Then msgbox("Share name " & strShareName & " already exists") errReturn = -4 Else 'colShares.Count <= 0 (actually only equal to zero) ' Create a link to the Win32_Share object Set objNewShare = objWMIService.Get("Win32_Share") ' Share the folder with the network errReturn = objNewShare.Create(strFolderName, strShareNa me, _ FILE_SHARE, MAXIMUM_CONNECTIONS, strShareDesc) End If 'colShares.Count <= 0 ' Free any memory used by variables Set colShares = Nothing End If 'strFolderName <> "" and objFSO.FolderExists(strFolderName) and strShareName <> "" ' Place an entry in the applications event log Question1LogEvent errReturn, "created", strFolderName, _ strShareName, strShareDesc ' Update TabQ1 to show the shares TabInit.Classname = "TabSelected" Question1Refresh TabInit.Classname = "TabUnselected" End Sub 'Q1aShareFolder '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 1 b) Deleting a Network Share '==== Purpose: To delete a network share '==== Inputs: The network share selected in SelectNetworkShares '==== Returns: Deletes the network share '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a share has been selected '==== Create a link to the share object that has the name that we have selected in the combo box cbQ1bSelectShare '==== Get the folder name and share description so that we can put inf o into event log '==== Delete the share object that has the name that we have selected in SelectNetworkShares '==== Select nothing in SelectNetworkShares '==== Free any memory used by variables '==== Place an entry in the applications event log '==== Update TabQ1 to show the current network shares '=============================================================================== ====================== '=============================================================================== ====================== Sub Q1bDeleteShare ' Header Section Dim colShares ' Collection of share ob jects Dim objShare ' A single share object Dim errReturn ' Error returned by func tion Dim strFolderName ' Folder name that is to be created Dim strShareName ' Share name that is to be created Dim strShareDesc ' Share description that is to be created ' Reference Section strFolderName = "" strShareName = SelectNetworkShares.value strShareDesc = "" 'Check that a share has been selected If strShareName = "" Then msgbox("Please select a share to delete") errReturn = -1 Else 'SelectNetworkShares.value <> "" ' Create a link to the share object that has the name that we have selected in t he combo box cbQ1bSelectShare Set objShare = objWMIService.Get("Win32_Share.Name='" &_ strShareName & "'") ' Get the folder name and share description so that we can put info into event l og strFolderName = objShare.Path strShareDesc = objShare.Description ' Delete the share object that has the name that we have selected in SelectNetwo rkShares errReturn = objShare.Delete ' Select nothing in SelectNetworkShares SelectNetworkShares.value="" ' Free any memory used by variables Set objShare = Nothing End If 'SelectNetworkShares.value <> "" ' Place an entry in the applications event log Question1LogEvent errReturn, "deleted", strFolderName, _ strShareName, strShareDesc ' Update TabQ1 to show the current network shares TabInit.Classname = "TabSelected" Question1Refresh TabInit.Classname = "TabUnselected" End Sub 'Q1bDeleteShare '=============================================================================== ====================== '=============================================================================== ====================== '==== Question1LogEvent '==== Purpose: To place an entry into the application event log reporti ng the result of Q1a and Q1b '==== Inputs: errNum: The error number '==== strLogText: 'created' or 'deleted' '==== Returns: Places an entry into the application event log '==== Pseudo code '==== Create a dictionary that contains error codes '==== Place an entry into the appliccation event log '==== Delete the dictionary to free memory '==== Update the view of the the event log on the screen ''============================================================================== ======================= '=============================================================================== ====================== Sub Question1LogEvent (errReturn, strLogText, strFolderName, _ strShareName, strShareDesc) ' Header Section Dim errDictionary ' A Dictionary of error codes ' Create a dictionary that contains error codes Set errDictionary = CreateObject("scripting.dictionary") errDictionary.Add 0, "Success" errDictionary.Add 2, "Access Denied" errDictionary.Add 8, "Unknown Failure" errDictionary.Add 9, "Invalid Name" errDictionary.Add 10, "Invalid Level" errDictionary.Add 21, "Invalid Parameter" errDictionary.Add 22, "Duplicate Share" errDictionary.Add 23, "Redirected Path" errDictionary.Add 24, "Unknown Device or Directory" errDictionary.Add 25, "Net Name Not Found" errDictionary.Add -1, "Blank Folder Name" errDictionary.Add -2, "Folder does not exist" errDictionary.Add -3, "Blank Share Name" errDictionary.Add -4, "Share already exists" ' Place an entry into the appliccation event log If errDictionary.exists(errReturn) Then If errDictionary.Item(errReturn) = "Success" Then objShell.LogEvent EVENT_SUCCESS, _ "Network Share " & strShareName & " " &_ strLogText & "." & vbNewline &_ vbTab & "Folder Name: " & strFolderName & vbNewl ine &_ vbTab & "Share Name: " & strShareName & vbNewlin e &_ vbTab & "Share Description: " & strShareDesc Else 'errDictionary.Item(errReturn) <> "Success" objShell.LogEvent EVENT_FAILED, _ "Network Share " & strShareName &_ " not " & strLogText & "." & vbNewline &_ vbTab & "Folder Name: " & strFolderName & vbNewl ine &_ vbTab & "Share Name: " & strShareName & vbNewlin e &_ vbTab & "Share Description: " & strShareDesc & v bNewline &_ "Error :" & errReturn & vbTab & errDictionary.It em(errReturn) End If 'errDictionary.Item(errReturn) <> "Success" Else 'Not errDictionary.exists(errReturn) objShell.LogEvent EVENT_FAILED, _ "Network Share " & strShareName &_ " not " & strLogText & "." & vbNewline &_ vbTab & "Folder Name: " & strFolderName & vbNewline &_ vbTab & "Share Name: " & strShareName & vbNewline &_ vbTab & "Share Description: " & strShareDesc & vbNewline &_ "Unknown Error :" & errReturn End If ''Not errDictionary.exists(errReturn) ' Delete the dictionary to free memory errDictionary.RemoveAll set errDictionary = Nothing ' Update the view of the the event log on the screen UpdateEventLog End Sub 'Question1LogEvent '=============================================================================== ====================== '=============================================================================== ====================== '==== Question2Refresh '==== Purpose: To put the list of network adapters ontoTabQ2 '==== Inputs: None '==== Returns: Places the list of network shares onto TabQ2 '==== Pseudo code '==== Clear any information out of the list of network adapters '==== Get the collection of network adapter objects from the cimv2 nam espace '==== Adjust the list size so that it can display all the network adap ters '==== Cycle through all the network adapters and place the names into the list of network adapters '==== Remember the index so that if there is one adapter, we can selec t it '==== If there is one network adapters, make sure it is selected '==== Otherwise, select nothing '==== Free any memory used by variables '=============================================================================== ====================== '=============================================================================== ====================== Sub Question2Refresh Dim arrNetAdaptersMacAddr() Dim arrNetAdaptersDescr() Dim colNetAdapters 'Collection of Network adapters Dim objNetAdapter 'An instance of a network adaptor Dim objOption Dim index ' Clear any information out of the list of network adapters For Each objOption in SelectNetAdapterMACAddress.options objOption.RemoveNode Next 'objOption ' Network adapter description was taking up too much space on the screen , so delete it from the code 'For Each objOption in SelectQ2NetAdapterDescription.options ' objOption.RemoveNode 'Next 'objOption For Each objOption in SelectNetAdapterDHCP.options objOption.RemoveNode Next 'objOption For Each objOption in SelectNetAdapterIPAddress.options objOption.RemoveNode Next 'objOption For Each objOption in SelectNetAdapterSubnetMask.options objOption.RemoveNode Next 'objOption For Each objOption in SelectNetAdapterGatewayAddress.options objOption.RemoveNode Next 'objOption For Each objOption in SelectNetAdapterDNSDomain.options objOption.RemoveNode Next 'objOption ' Get the collection of network adapter objects from the cimv2 namespace Set colNetAdapters = objWMIService.ExecQuery _ ("Select * from Win32_NetworkAdapterConfiguration " &_ "where IPEnabled=TRUE") ' Adjust the list size so that it can display all the network adapters SelectNetAdapterMACAddress.size = colNetAdapters.Count + 1 ' Network adapter description was taking up too much space on the screen , so delete it from the code ' SelectQ2NetAdapterDescription.size = colNetAdapters.Count + 1 SelectNetAdapterDHCP.size = colNetAdapters.Count + 1 SelectNetAdapterIPAddress.size = colNetAdapters.Count + 1 SelectNetAdapterSubnetMask.size = colNetAdapters.Count + 1 SelectNetAdapterGatewayAddress.size = colNetAdapters.Count + 1 SelectNetAdapterDNSDomain.size = colNetAdapters.Count + 1 ' Cycle through all the network adapters and place the names into the list of ne twork adapters For Each objNetAdapter In colNetAdapters ' A Select element in HTML is made up of a collection of Option elements ' An option element has a number of attributes. We will use two of the attributes - Text and Value ' The Text attribute is what will be displayed, while the Value attribute is the part ' that is used to process what is to be done ' We will set the value option of all the lists to objNetAdapter .Index so that all the lists are linked set objOption = document.createElement("option") objOption.text = objNetAdapter.MACAddress objOption.value = objNetAdapter.Index ' Remember the index so that if there is one adapter, we can select it index = objNetAdapter.Index SelectNetAdapterMACAddress.add(objOption) ' Debug AddToInitLog "Q2_NetAdapter: " & objNetAdapter.MACAddress ' Network adapter description was taking up too much space on th e screen, so delete it from the code 'set objOption = document.createElement("option") 'objOption.text = objNetAdapter.Description 'objOption.value = objNetAdapter.Index 'SelectQ2NetAdapterDescription.add(objOption) set objOption = document.createElement("option") If objNetAdapter.DHCPEnabled Then objOption.text = "DHCP" Else ' Not objNetAdapter.DHCPEnabled objOption.text = "Manual" End If ' Not objNetAdapter.DHCPEnabled objOption.value = objNetAdapter.Index SelectNetAdapterDHCP.add(objOption) set objOption = document.createElement("option") objOption.text = join(objNetAdapter.IPAddress) objOption.value = objNetAdapter.Index SelectNetAdapterIPAddress.add(objOption) set objOption = document.createElement("option") objOption.text = join(objNetAdapter.IPSubnet) objOption.value = objNetAdapter.Index SelectNetAdapterSubnetMask.add(objOption) set objOption = document.createElement("option") if isnull(objNetAdapter.DefaultIPGateway) Then objOption.text = "null" Else ' not isnull(objNetAdapter.DefaultIPGateway) objOption.text = join(objNetAdapter.DefaultIPGateway) End If ' not isnull(objNetAdapter.DefaultIPGateway) objOption.value = objNetAdapter.Index SelectNetAdapterGatewayAddress.add(objOption) set objOption = document.createElement("option") objOption.text = objNetAdapter.DNSDomain objOption.value = objNetAdapter.Index SelectNetAdapterDNSDomain.add(objOption) Next 'objNetAdapter ' If there is one network adapters, make sure it is selected If SelectNetAdapterMACAddress.Options.length = 1 Then SelectNetAdapterMACAddress.Value = index ' Network adapter description was taking up too much space on t he screen, so delete it from the code 'SelectQ2NetAdapterDescription.Value = index SelectNetAdapterDHCP.Value = index SelectNetAdapterIPAddress.Value = index SelectNetAdapterSubnetMask.Value = index SelectNetAdapterGatewayAddress.Value = index SelectNetAdapterDNSDomain.Value = index Else 'SelectNetAdapterMACAddress.Options.length <> 1 SelectNetAdapterMACAddress.Value = "" ' Network adapter description was taking up too much space on t he screen, so delete it from the code 'SelectQ2NetAdapterDescription.Value = "" SelectNetAdapterDHCP.Value = "" SelectNetAdapterIPAddress.Value = "" SelectNetAdapterSubnetMask.Value = "" SelectNetAdapterGatewayAddress.Value = "" SelectNetAdapterDNSDomain.Value = "" End If 'SelectNetAdapterMACAddress.Options.length <> 1 ' Free any memory used by variables Set colNetAdapters = Nothing ' Adjust the html elements so that the event log is in the correct place on the screen End Sub 'Question2Refresh '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 2 a) Configure a static IP and Gateway '==== Purpose: To configure a network adapter to have a static IP addre ss and gateway '==== Inputs: SelectNetAdapterMACAddress.Value '==== txtQ2aIPAddress.value '==== txtQ2aSubnetMask.value '==== Returns: Network Adapter with a ststic IP address and gateway '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a network adapter has been selected '==== Check that an IP address has been specified '==== Check that a subnet mask has been specified '==== Get user input of IP address, subnet mask and gateway and conver t to array '==== Get the network adapter object from the cimv2 namespace that is enabled '==== and has the Mac Address we have chosen '==== Set the IP address, subnet mask and gateway in the shares that h ave '==== the selected network adapter's index '==== Free any memory used by variables '==== Place an entry in the applications event log '==== Update TabQ2 to show the current network shares '=============================================================================== ====================== '=============================================================================== ====================== Sub Q2aConfigureStatic Dim strMacAddress ' String containing the Mac Address of t he adapter Dim strIPAddress ' Array of strings containing the IP add ress (only one element) Dim strSubnetMask ' Array of strings containing the subnet mask (only one element) Dim strGateway ' Array of strings containing the gatewa y address (only one element) Dim strGatewayMetric ' Array of gateway metrics Dim objNetAdapter ' An instance of a network adaptor Dim errEnable ' error returned when calling the objNet Adapter.EnableStatic method Dim errGateways ' error returned when calling the objNet Adapter.SetGateways method ' Check that a network adapter has been selected If SelectNetAdapterMACAddress.Value = "" Then errEnable = -1 'We haven't selected any network adapter yet ' Check that an IP address has been specified ElseIf txtQ2aIPAddress.value = "" Then errEnable = -2 'We don't want an empty IP address ' Check that a subnet mask has been specified ElseIf txtQ2aSubnetMask.value = "" Then errEnable = -3 'We need a subnet mask Else 'MACAddress.Value <> "" and IPAddress.value <> "" and SubnetMask .value <> "" ' Get user input of IP address, subnet mask and gateway and convert to array strIPAddress = Array(txtQ2aIPAddress.value) strSubnetMask = Array(txtQ2aSubnetMask.value) strGateway = Array(txtQ2aGatewayAddress.value) strGatewayMetric = Array(1) 'We are only setting one gateway address ' Get the network adapter object from the cimv2 namespace that is enabled and ha s the Mac Address we have chosen Set objNetAdapter = objWMIService.Get _ ("Win32_NetworkAdapterConfiguration.Index=" &_ SelectNetAdapterMACAddress.Value) ' Set the IP address, subnet mask and gateway in the shares that have the select ed network adapter's index errEnable = objNetAdapter.EnableStatic(strIPAddress, strSubnetMa sk) errGateways = objNetAdapter.SetGateways(strGateway, strGatewayme tric) ' Free any memory used by variables Set objNetAdapter = Nothing End If ''MACAddress.Value <> "" and IPAddress.value <> "" and SubnetMas k.value <> "" Q2EventLog errEnable, "static network address" Q2EventLog errGateways, "gateway address" ' Update TabQ2 to show the current network shares TabInit.Classname = "TabSelected" Question2Refresh TabInit.Classname = "TabUnselected" End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Q2aConfigureDHCP '==== This is not part of the assignment, but it makes it easier to te st if the user interface if we can '==== switch an adapter between static and DHCP '==== Purpose: To configure a network adapter to have DHCP '==== Inputs: SelectNetAdapterMACAddress.Value '==== Returns: Network Adapter with DHCP '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a network adapter has been selected '==== Get the collection of enabled network adapter objects with the s elected network adapter's index '==== Check that the network adapter exists '==== Set our collection of shares hat have the selected network adapt er's index to DHCP '==== Free any memory used by variables '==== Place an entry in the applications event log '==== Update TabQ2 to show the current network shares '=============================================================================== ====================== '=============================================================================== ====================== Sub Q2aConfigureDHCP Dim objNetAdapter 'An instance of a network adaptor Dim errEnable 'error returned when calling the objNetA dapter.EnableStatic method Dim errGateways 'error returned when calling the objNetA dapter.SetGateways method ' Check that a network adapter has been selected If SelectNetAdapterMACAddress.Value = "" Then errEnable = -1 'We haven't selected any network adapter yet Else ' SelectNetAdapterMACAddress.Value <> "" 'Get the collection of enabled network adapter objects with the selected network adapter's index Set objNetAdapter = objWMIService.Get _ ("Win32_NetworkAdapterConfiguration.Index=" &_ SelectNetAdapterMACAddress.Value) ' Set the selected network adapter's index to DHCP errEnable = objNetAdapter.EnableDHCP() ' Free any memory used by variables Set objNetAdapter = Nothing End If ' SelectNetAdapterMACAddress.Value <> "" ' Place an entry in the applications event log Q2EventLog errEnable, "DHCP" ' Update TabQ2 to show the current network shares TabInit.Classname = "TabSelected" Question2Refresh TabInit.Classname = "TabUnselected" End Sub ' Q2aConfigureDHCP '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 2 b) Assign a DNS domain for your network adaptor '==== Purpose: To configure a DNS domain for a network adapter '==== Inputs: SelectNetAdapterMACAddress.Value '==== txtQ2bDNSDomainName.value '==== Returns: Network Adapter with DHCP '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a network adapter has been selected '==== Check that a domain name has been specified '==== Get the collection of enabled network adapter objects with the s elected network adapter's index '==== Check that the network adapter exists '==== Set our collection of shares hat have the selected network adapt er's index to have the DNS domain '==== Free any memory used by variables '==== Place an entry in the applications event log '==== Update TabQ2 to show the current network shares '=============================================================================== ====================== '=============================================================================== ====================== Sub Q2bAssignDNSDomainName Dim colNetAdapters 'Collection of Network adapters Dim objNetAdapter 'An instance of a network adaptor Dim errAssign 'error returned when calling the objNetA dapter.EnableStatic method ' Check that a network adapter has been selected If SelectNetAdapterMACAddress.Value = "" Then errAssign = -1 'We haven't selected any network adapter yet ' Check that a domain name has been specified ElseIf txtQ2bDNSDomainName.value = "" Then errAssign = -5 ' We haven't specified a domain name Else ' SelectNetAdapterMACAddress.Value = The Index of the network ad apter selected ' Get the collection of enabled network adapter objects with the selected networ k adapter's index Set colNetAdapters = objWMIService.ExecQuery _ ("Select * from Win32_NetworkAdapterConfiguration " &_ "where IPEnabled=TRUE " &_ "AND Index = " & Int(SelectNetAdapterMACAddress.Value)) ' Check that the network adapter exists If ColNetAdapters.Count=0 Then errAssign = -4 Else ' Network adapter exists and is enabled ' Set our collection of shares hat have the selected network adapter's index to have the DNS domain For Each objNetAdapter in ColNetAdapters errAssign = objNetAdapter.SetDNSDomain _ (txtQ2bDNSDomainName.value) Next 'objNetAdapter End If ' Network adapter exists and is enabled ' Free any memory used by variables Set colNetAdapters = Nothing End If ''SelectNetAdapterMACAddress.Value = The Index of the network ad apter selected ' Place an entry in the applications event log Q2EventLog errAssign, "DNS Domain" ' Update TabQ2 to show the current network shares TabInit.Classname = "TabSelected" Question2Refresh TabInit.Classname = "TabUnselected" End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Question2LogEvent '==== Purpose: To place an entry into the application event log reporti ng the result of Q2a and Q2b '==== Inputs: errNum: The error number '==== strLogText: 'static network address' or 'gateway add ress' or 'DHCP' or 'DNS Domain' '==== Returns: Places an entry into the application event log '==== Pseudo code '==== Create a dictionary that contains error codes '==== Put information into strLogDetails '==== Place an entry into the application event log '==== Delete the dictionary '==== Update the view of the the event log on the screen ''============================================================================== ======================= '=============================================================================== ====================== Sub Q2EventLog (errReturn, strLogText) ' Header Section Dim errDictionary ' Dictionary containing error values Dim strLogDetails ' string containing text to write to the application event log ' Create a dictionary that contains error codes Set errDictionary = CreateObject("scripting.dictionary") errDictionary.Add -1, "No Network Adapter Selected" errDictionary.Add -2, "Empty IP Address" errDictionary.Add -3, "Empty Subnet mask" errDictionary.Add -4, "Invalid Network Adapter Selected" errDictionary.Add -5, "Empty DNS Domain name" errDictionary.Add 0, "Successful completion, no reboot required" errDictionary.Add 1, "Successful completion, reboot required" errDictionary.Add 64, "Method not supported on this platform" errDictionary.Add 65, "Unknown failure" errDictionary.Add 66, "Invalid subnet mask" errDictionary.Add 67, "An error occurred while processing " &_ "an Instance that was re turned" errDictionary.Add 68, "Invalid input parameter" errDictionary.Add 69, "More than 5 gateways specified" errDictionary.Add 70, "Invalid IP address" errDictionary.Add 71, "Invalid gateway IP address" errDictionary.Add 72, "An error occurred while accessing the " &_ "Registry for the reques ted information" errDictionary.Add 73, "Invalid domain name" errDictionary.Add 74, "Invalid host name" errDictionary.Add 75, "No primary/secondary WINS server defined" errDictionary.Add 76, "Invalid file" errDictionary.Add 77, "Invalid system path" errDictionary.Add 78, "File copy failed" errDictionary.Add 79, "Invalid security parameter" errDictionary.Add 80, "Unable to configure TCP/IP service" errDictionary.Add 81, "Unable to configure DHCP service" errDictionary.Add 82, "Unable to renew DHCP lease" errDictionary.Add 83, "Unable to release DHCP lease" errDictionary.Add 84, "IP not enabled on adapter" errDictionary.Add 85, "IPX not enabled on adapter" errDictionary.Add 86, "Frame/network number bounds error" errDictionary.Add 87, "Invalid frame type" errDictionary.Add 88, "Invalid network number" errDictionary.Add 89, "Duplicate network number" errDictionary.Add 90, "Parameter out of bounds" errDictionary.Add 91, "Access denied" errDictionary.Add 92, "Out of memory" errDictionary.Add 93, "Already exists" errDictionary.Add 94, "Path, file or object not found" errDictionary.Add 95, "Unable to notify service" errDictionary.Add 96, "Unable to notify DNS service" errDictionary.Add 97, "Interface not configurable" errDictionary.Add 98, "Not all DHCP leases could be released/renewed" errDictionary.Add 100, "DHCP not enabled on adapter" ' Put information into strLogDetails ' strLogText contains different information depending on which subroutine called it Select Case strLogText Case "static network address" strLogDetails = strLogText & vbNewLine &_ vbTab & "MACAddress: "& SelectNetAdapterMACAddress.inne rText &_ vbNewLine &_ vbTab & "IP Address: "& txtQ2aIPAddress.value & vbNewLi ne &_ vbTab & "Subnet Mask: "& txtQ2aSubnetMask.value & vbNew Line Case "gateway address" strLogDetails = strLogText & vbNewLine &_ vbTab & "MACAddress: "& SelectNetAdapterMACAddress.inne rText &_ vbNewLine &_ vbTab & "Gateway Address: "& txtQ2aGatewayAddress.Value & vbNewLine Case "DHCP" strLogDetails = strLogText & vbNewLine &_ vbTab & "MACAddress: "& SelectNetAdapterMACAddress.inne rText &_ vbNewLine Case "DNS Domain" strLogDetails = strLogText & vbNewLine &_ vbTab & "MACAddress: "& SelectNetAdapterMACAddress.inne rText &_ vbNewLine &_ vbTab & "DNS Domain Name: "& txtQ2bDNSDomainName.Value & vbNewLine Case Else End Select ' Place an entry into the application event log If errDictionary.exists(errReturn) Then If errReturn = 0 or errReturn = 1 Then objShell.LogEvent EVENT_SUCCESS, _ "Successfully configured " & strLogDetails &_ vbTab & errReturn & ": " &_ errDictionary.Item(errReturn) Else objShell.LogEvent EVENT_FAILED, _ "Could not configure " & strLogDetails &_ vbTab & errReturn & ": " &_ errDictionary.Item(errReturn) End If Else objShell.LogEvent EVENT_FAILED, _ "Could not configured " & strLogDetails &_ vbTab & "Unknown Error " & errReturn End If errDictionary.RemoveAll set errDictionary = Nothing ' Update the view of the the event log on the screen UpdateEventLog End Sub ' Q2EventLog '=============================================================================== ====================== '=============================================================================== ====================== '==== Question3Refresh '==== Purpose: To put information about the current workgroup/domain on toTabQ3 '==== Inputs: None '==== Returns: Displays whether a domain or workgroup is connected onto TabQ3 '==== Displays domain or workgroup name onto TabQ3 '==== Displays domain or workgroup username onto TabQ3 '==== Pseudo code '==== Get the name of this workstation '==== Get the Win32_ComputerSystem object from the cimv2 namespace whe re name = this computer '==== Work out if the computer is connected to a domain or a workgroup '==== If it is a domain, then display that is is connected to a domain , the domain name and the username '==== Otherwise, display that is is connected to a workgroup, the work group name and the username '==== Free any memory used by variables '=============================================================================== ====================== '=============================================================================== ====================== Sub Question3Refresh ' Header Section Dim strComputer Dim objComputer ' Get the name of this workstation strComputer = objNetwork.ComputerName ' Get the Win32_ComputerSystem object from the cimv2 namespace where name = this computer Set objComputer = objWMIService.Get _ ("Win32_ComputerSystem.Name='" & strComputer & "'") ' Work out if the computer is connected to a domain or a workgroup If objComputer.PartOfDomain Then ' If it is a domain, then display that is is connected to a domain, the domain n ame and the username LabelDomainOrWorkgroup.InnerText = "Domain" LabelDorW.InnerText = "Domain Name: " LabelDomainOrWorkgroupName.InnerText = objComputer.Domain LabelUsername.InnerText = objComputer.UserName ' Debug AddToInitLog "Q3_Domain: " & objComputer.Domain & ", Username: " & objComputer.UserName Else ' Otherwise, display that is is connected to a workgroup, the workgroup name and the username LabelDomainOrWorkgroup.InnerText = "Workgroup" LabelDorW.InnerText = "Workgroup Name: " LabelDomainOrWorkgroupName.InnerText = objComputer.Workgroup LabelUsername.InnerText = objComputer.UserName LabelDomainOrWorkgroupName.innerText = "" ' Update the tex t field on TabQ4 LabelDomainOrWorkgroupName.innerText = "" ' Update the tex t field on TabQ5 LabelDomainOrWorkgroupName.innerText = "" ' Update the tex t field on TabQ6 ' Debug AddToInitLog "Q3_Workgroup: " & objComputer.Workgroup & ", Usern ame: " & objComputer.UserName End If Q5cRefreshServers ' Update the server list on TabQ5 ' Q6aListOUs ' Update the list of OUs in the domain o n TabQ6 ' Free any memory used by variables Set objComputer = Nothing End Sub ' Question3Refresh '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 3 a) Join your workstation to the "galaxy.local" domain '==== Purpose: Join your workstation to the domain specified on the Tab Q3 '==== Inputs: SelectNetAdapterMACAddress.Value '==== txtQ2bDNSDomainName.value '==== Returns: Workstation connected to the domain specified on the Tab Q3 '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a Domain has been specified '==== Check that a Username has been specified '==== Get the name of this workstation '==== Get the Win32_ComputerSystem object from the cimv2 namespace whe re name = this computer '==== Join the computer to the domain '==== Free any memory used by variables '==== Place an entry in the applications event log '==== Update TabQ3 to show the current workgroup/domain '=============================================================================== ====================== '=============================================================================== ====================== Sub Q3aJoinDomain Const JOIN_DOMAIN = 1 Const ACCT_CREATE = 2 Const ACCT_DELETE = 4 Const WIN9X_UPGRADE = 16 Const DOMAIN_JOIN_IF_JOINED = 32 Const JOIN_UNSECURE = 64 Const MACHINE_PASSWORD_PASSED = 128 Const DEFERRED_SPN_SET = 256 Const INSTALL_INVOCATION = 262144 Dim errReturn Dim strComputer Dim objComputer Dim ReturnValue ' Check that a Domain has been specified If txtQ3aDomain.value = "" Then errReturn = -1 ' Check that a Username has been specified ElseIf txtQ3aUsername.value = "" Then errReturn = -2 Else ' txtQ3aDomain.value <> "" and txtQ3aUsername.value <> "" ' Get the name of this workstation strComputer = objNetwork.ComputerName ' Get the Win32_ComputerSystem object from the cimv2 namespace where name = this computer Set objComputer = objWMIService.Get _ ("Win32_ComputerSystem.Name='" & strComputer & "'") ' Join the computer to the domain errReturn = objComputer.JoinDomainOrWorkGroup(txtQ3aDomain.value , _ pwdQ3aPassword.value, _ txtQ3aDomain.value & "\" & txtQ3aUsername.value, _ NULL, _ JOIN_DOMAIN + ACCT_CREATE) ' Free any memory used by variables Set objComputer = Nothing End If ' txtQ3aDomain.value <> "" and txtQ3aUsername.value <> "" ' Place an entry in the applications event log Select Case errReturn Case 0 'If the domain was successfully joined, then place an en try in the applications log 'Create the success log entry with the IP address, the S ubnet Mask and the Gateway address objShell.LogEvent EVENT_SUCCESS, _ "Domain successfully joined." & vbNewLine &_ vbTab & "Domain: "& txtQ3aDomain.value & vbNewLine &_ vbTab & "Username: "& txtQ3aUsername.value & vbNewL ine &_ vbTab & "Password: ********" 'Password should not be stored in event log Case -1 ' The domain name was not specified objShell.LogEvent EVENT_SUCCESS, _ "Could not join domain as domain name was not sp ecified." Case -2 ' The domain username was not specified objShell.LogEvent EVENT_SUCCESS, _ "Could not join domain " & txtQ3aDomain.value &_ " as username was not specified." Case Else 'Otherwise, create a failure log entry with the IP addre ss, the Subnet Mask and the Gateway address objShell.LogEvent EVENT_FAILED, _ "Could not join domain." & vbNewLine &_ vbTab & "Domain: "& txtQ3aDomain.value & vbNewLine &_ vbTab & "Username: "& txtQ3aUsername.value & vbNewL ine &_ vbTab & "Password: ********" &_ vbTab & "Error Number: " & errReturn End Select ' Update the view of the the event log on the screen UpdateEventLog ' Update TabQ3 to show the current workgroup/domain ClearInitLog TabInit.Classname = "TabSelected" Question3Refresh TabInit.Classname = "TabUnselected" End Sub ' Q3aJoinDomain '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 3 b) Unjoin your workstation from the class domain '==== Purpose: Unjoin your workstation from the domain '==== Inputs: None '==== Returns: Workstation not connected to any domain '==== Places an event in the Application Event Log '==== Pseudo code '==== Get the name of this workstation '==== Get the Win32_ComputerSystem object from the cimv2 namespace whe re name = this computer '==== Unjoin the computer to the domain '==== Free any memory used by variables '==== Place an entry in the applications event log '==== Update TabQ3 to show the current workgroup/domain '=============================================================================== ====================== '=============================================================================== ====================== Sub Q3bUnjoinDomain Const NETSETUP_ACCT_DELETE = 2 Dim errReturn Dim strComputer Dim objComputer ' Check that a Domain has been specified If txtQ3aDomain.value = "" Then errReturn = -1 ' Check that a Username has been specified ElseIf txtQ3aUsername.value = "" Then errReturn = -2 Else ' txtQ3aDomain.value <> "" and txtQ3aUsername.value <> "" ' Get the name of this workstation strComputer = objNetwork.ComputerName ' Get the Win32_ComputerSystem object from the cimv2 namespace where name = this computer Set objComputer = objWMIService.Get _ ("Win32_ComputerSystem.Name='" & strComputer & "'") ' Unjoin the computer to the domain errReturn = objComputer.UnJoinDomainOrWorkGroup _ (pwdQ3aPassword.value, _ txtQ3aDomain.value & "\" & txtQ3aUsername.value, _ NETSETUP_ACCT_DELETE) ' Free any memory used by variables Set objComputer = Nothing End If ' txtQ3aDomain.value <> "" and txtQ3aUsername.value <> "" ' Place an entry in the applications event log ' 1326 = Unknown username or password ' 1355 = The specified domain either does not exist or could not be contacted ' 2691 = This computer is already a Domain member If errReturn = 0 Then 'If the domain was successfully joined, then place an entry in t he applications log 'Create the success log entry with the IP address, the Subnet Ma sk and the Gateway address objShell.LogEvent EVENT_SUCCESS, _ "Domain successfully unjoined." & vbNewLine &_ vbTab & "Domain: "& txtQ3aDomain.value & vbNewLine Else 'Otherwise, create a failure log entry with the IP address, the Subnet Mask and the Gateway address objShell.LogEvent EVENT_FAILED, _ "Could not unjoin domain." & vbNewLine &_ vbTab & "Domain: "& txtQ3aDomain.value & vbNewLine End If ' Update the view of the the event log on the screen UpdateEventLog ' Update TabQ3 to show the current workgroup/domain ClearInitLog TabInit.Classname = "TabSelected" Question3Refresh TabInit.Classname = "TabUnselected" End Sub ' Q3bUnjoinDomain '=============================================================================== ====================== '=============================================================================== ====================== '==== Question4Refresh '=============================================================================== ====================== '=============================================================================== ====================== Sub Question4Refresh Q4bListOUs End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 4 a) Create an OU ... Name it with your surname '==== Purpose: Create an Organisational Unit with a name that is define d in TabQ4 '==== Inputs: LabelDomainOrWorkgroupName.innerText The domain where we will be creating the OU '==== txtQ4aOUName.value The name of the OU that we want to create '==== txtQ4aOUDescription The description that we will giv e to the new OU '==== Returns: A new OU in the specified domain '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a Domain has been specified '==== Check that a OU name has been specified '==== Convert LabelDomainOrWorkgroupName.innerText to fully qualified domain name '==== Convert txtQ4aOUName.value to fully qualified domain name '==== Link to the object defined by the provider and the OU and the do main '==== Create the new OU and return a handle to it '==== Modify the description of the OU '==== Commit the change to Active Directory '==== Free any memory used by variables '==== Place an entry in the applications event log '==== Update TabQ4 to show the current workgroup/domain '=============================================================================== ====================== '=============================================================================== ====================== Sub Q4aAddOU 'Header Section On Error Resume Next Dim strProvider ' defines how will talk to Active Directory Dim strOU ' path to where new object will be creat ed Dim strDomain ' name of Domain connecting to Dim strClass ' the class of object we are creating Dim strOUname ' name of object are creating Dim strODescription ' name of object are creating Dim objDomain ' holds connection to adsi Dim objOU ' holds handle to create method Dim errReturn 'Reference Section strProvider = "LDAP://" ' Lightweight Directory Access P rotocol provider strClass = "organizationalUnit" ' Class of object being created is an Or ganisationalUnit strOU = "" ' Path to where new object will be created is th e root of the specified domain ' Check that a Domain has been specified If LabelDomainOrWorkgroupName.innerText = "" Then errReturn = -1 ' Check that a OU name has been specified ElseIf txtQ4aOUName.value = "" Then errReturn = -2 Else ' LabelDomainOrWorkgroupName.innerText <> "" and txtQ4aOUName.va lue <> "" ' Convert LabelDomainOrWorkgroupName.innerText to fully qualified domain name strDomain = "dc=" & LabelDomainOrWorkgroupName.innerText strDomain = Replace(strDomain,".",",dc=") ' Convert txtQ4aOUName.value to fully qualified domain name strOUname = "OU=" & txtQ4aOUName.value ' Link to the object defined by the provider and the OU and the domain Set objDomain = GetObject(strProvider & strOU & strDomain) errReturn = Err.Number If errReturn = 0 Then ' Create the new OU and return a handle to it Set objOU = objDomain.create(strClass, strOUname) errReturn = Err.Number If errReturn = 0 Then ' Modify the description of the OU objOU.Put "Description", txtQ4aOUDescription.val ue errReturn = Err.Number If errReturn = 0 Then ' Commit the change to Active Directory objOU.SetInfo errReturn = Err.Number TabInit.Classname = "TabSelected" Q4bListOUs SelectOUs.value = txtQ4aOUName.value TabInit.Classname = "TabUnselected" End If End If ' Free any memory used by variables Set objOU = Nothing End If Set objDomain = Nothing End If on error goto 0 ' Place an entry in the applications event log Select Case errReturn Case 0 objShell.LogEvent EVENT_SUCCESS, _ "OU " & strOUname & " successfully created in " &_ strProvider & strOU & strDomain Case -1 objShell.LogEvent EVENT_FAILED, _ "OU " & strOUname &_ " not created as the domain name was not specifi ed." Case -2 objShell.LogEvent EVENT_FAILED, _ "OU not created as the OU name was not specified ." Case -2147019886 objShell.LogEvent EVENT_FAILED, _ "OU " & strOUname &_ " already exists in " & strProvider & strOU & st rDomain &_ " and cannot be created." Case Else objShell.LogEvent EVENT_FAILED, _ "OU " & strOUname &_ " could not be created in " & strProvider & strO U &_ strDomain & " error on the play " & errRetur n End Select TabInit.Classname = "TabSelected" Q4bListOUs TabInit.Classname = "TabUnselected" End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Q4bListOUs '==== Purpose: To list the OUs in a domain on TabQ4 '==== Inputs: LabelDomainOrWorkgroupName.innerText The domain where we will be creating the OU '==== Returns: A list of OUs in the specified domain on TabQ4 '==== Pseudo code '==== Clear the list of OUs on TabQ4 '==== Check that a Domain has been specified '==== Convert LabelDomainOrWorkgroupName.innerText to fully qualified domain name '==== Connect to the active directory provider '==== Get a collection of OUs defined by the provider and the domain '==== Cycle through the list of OUs '==== Place the OU name into SelectOUs '==== Free any memory used by variables '==== Select the OU from task 4a by default '==== List the users of the selectedOU '=============================================================================== ====================== '=============================================================================== ====================== Sub Q4bListOUs ' Header Section Dim objOption Dim strDomain Dim objConnection Dim objCommand Const ADS_SCOPE_SUBTREE = 2 ' Clear the list ofOUs on TabQ4 For Each objOption in SelectOUs.options objOption.RemoveNode Next 'objOption ' Check that a Domain has been specified If LabelDomainOrWorkgroupName.innerText <> "" Then ' Convert LabelDomainOrWorkgroupName.innerText to fully qualified domain name strDomain = "dc=" & LabelDomainOrWorkgroupName.innerText strDomain = Replace(strDomain,".",",dc=") ' Connect to the active directory provider Set objConnection = CreateObject("ADODB.Connection") Set objCommand = CreateObject("ADODB.Command") objConnection.Provider = "ADsDSOObject" objConnection.Open "Active Directory Provider" Set objCommand.ActiveConnection = objConnection objCommand.Properties("Page Size") = 1000 objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE ' Get a collection of OUs defined by the provider and the domain objCommand.CommandText = _ "SELECT Name, ADsPath FROM 'LDAP://" & strDomain & "'" & _ " WHERE objectCategory='organizationalUnit' ORDE R BY Name" Set objOURecordSet = objCommand.Execute ' Get a collection of Users defined by the provider and the domain objCommand.CommandText = _ "SELECT Name, ADsPath FROM 'LDAP://" & strDomain & "'" & _ " WHERE objectCategory='user' ORDER BY Name" Set objUserRecordSet = objCommand.Execute SelectOUs.size = 1 ' Cycle through the list of OUs objOURecordSet.MoveFirst Do Until objOURecordSet.EOF ' Place the OU name into SelectOUs Set objOption = Document.createElement("OPTION") objOption.Text = objOURecordSet.Fields("Name").Value objOption.Value = objOURecordSet.Fields("Name").Value SelectOUs.Add(objOption) ' Debug AddToInitLog "Q4b_OU: " & objOURecordSet.Fields("Name"). Value objOURecordSet.MoveNext Loop ' Free any memory used by variables objOURecordSet.close Set objOURecordSet = Nothing ' Set the OU to nothing by default SelectOUs.value = "" End If Q4bListUsers End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Q4bListUsers '==== Purpose: To list the users in a domain on TabQ4 '==== Inputs: LabelDomainOrWorkgroupName.innerText The domain where we will be creating the user '==== SelectOUs.value The OU where we will be creating the use r '==== Returns: A list of users in the specified domain and OU on TabQ4 '==== Pseudo code '==== Clear the list of users on TabQ4 '==== Check that a Domain and OU has been specified '==== Convert LabelDomainOrWorkgroupName.innerText and SelectOUs.value to fully qualified domain name '==== Get a collection of users defined by the provider and the domain and the OU '==== Cycle through the list of users '==== Place the user name into SelectUsers '==== Free any memory used by variables '==== Select nothing by default '=============================================================================== ====================== '=============================================================================== ====================== Sub Q4bListUsers ' Header Section Dim objOption Dim strDomain Dim objConnection Dim objCommand Dim strFQDN Const ADS_SCOPE_SUBTREE = 2 ' Clear the list ofusers on TabQ4 For Each objOption in SelectUsers.options objOption.RemoveNode Next 'objOption For Each objOption in SelectUserOUs.options objOption.RemoveNode Next 'objOption ' Check that a Domain and OU has been specified If LabelDomainOrWorkgroupName.innerText <> "" and SelectOUs.value <> "" Then ' Convert LabelDomainOrWorkgroupName.innerText and SelectOUs.value to fully qual ified domain name strDomain = "dc=" & LabelDomainOrWorkgroupName.innerText strDomain = Replace(strDomain,".",",dc=") ' Connect to the active directory provider Set objConnection = CreateObject("ADODB.Connection") Set objCommand = CreateObject("ADODB.Command") objConnection.Provider = "ADsDSOObject" objConnection.Open "Active Directory Provider" Set objCommand.ActiveConnection = objConnection objCommand.Properties("Page Size") = 1000 objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE ' Get a collection of Users defined by the provider and the domain objCommand.CommandText = _ "SELECT Name, ADsPath FROM 'LDAP://" & strDomain & "'" & _ " WHERE objectCategory='user' ORDER BY Name" Set objUserRecordSet = objCommand.Execute SelectUsers.size = 1 ' Cycle through the list of users if not objUserRecordSet.BOF then objUserRecordSet.MoveFirst strFQDN = "" Do Until objUserRecordSet.EOF msgbox(objUserRecordSet.Fields("Name").Value & vbtab & objUserRecordSet.Fields(" ADsPath").Value) ' Place the user name into SelectUsers SelectUsers.size = SelectUsers.size + 1 Set objOption = Document.createElement("OPTION") objOption.Text = objUserRecordSet.Fields("Name") .Value objOption.Value = objUserRecordSet.Fields("ADsPa th").Value SelectUsers.Add(objOption) Set objOption = Document.createElement("OPTION") objOption.Text = mid(objUserRecordSet.Fields("AD sPath").Value, _ instr(1,objUserRecordSet.Fields("ADsPath ").Value,replace(objUserRecordSet.Fields("Name").Value,",","\,")) _ + len(replace(objUserRecordSet.Fields("N ame").Value,",","\,"))+1) objOption.Value = objUserRecordSet.Fields("ADsPa th").Value SelectUserOUs.Add(objOption) If objUserRecordSet.Fields("Name").Value = txtQ4 bUserName.Value Then strFQDN = objUserRecordSet.Fields("ADsPa th").Value End If ' Debug AddToInitLog "Q4b_Users: " & objUserRecordSet.Fi elds("ADsPath").Value objUserRecordSet.MoveNext Loop End If ' Free any memory used by variables objUserRecordSet.close Set objUserRecordSet = Nothing ' Select nothing by default SelectUsers.value = "" End If End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 4 b) Create a domain user in your OU '==== Purpose: Create an Organisational Unit with a name that is define d in TabQ4 '==== Inputs: LabelDomainOrWorkgroupName.innerText The domain where we will be creating the domain user '==== txtQ4aOUName.value The name of the OU where we will be creating the domain user '==== txtQ4bUserName The name of the domain user that we want to create '==== Returns: A new domain user in the specified domain and OU '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a Domain has been specified '==== Check that a domain user name has been specified '==== Convert LabelDomainOrWorkgroupName.innerText to fully qualified domain name '==== Convert txtQ4aOUName.value to fully qualified domain name '==== Link to the object defined by the provider and the OU and the do main '==== Create a new user and return a handle to it '==== Modify the account name of the user '==== Commit the change to Active Directory '==== Free any memory used by variables '==== Place an entry in the applications event log '==== Update TabQ4 to show the current workgroup/domain '=============================================================================== ====================== '=============================================================================== ====================== Sub Q4bAddUser 'Header Section On Error Resume Next Dim strProvider ' defines how will talk to Active Directory Dim strOU ' path to where new object will be creat ed Dim strDomain ' name of Domain connecting to Dim strClass ' the class of object we are creating Dim strCNname ' name of object are creating Dim objDomain ' holds connection to adsi Dim objOU ' holds handle to create method Dim strOUname ' holds the name of the OU that holds the user b eing created 'Reference Section strProvider = "LDAP://" 'Lightweight Directory Access Protocol p rovider strClass = "user" 'Class of object being created i s a user ' Check that a Domain has been specified If LabelDomainOrWorkgroupName.innerText = "" Then errReturn = -1 ' Check that a OU name has been specified ElseIf SelectOUs.value = "" Then errReturn = -2 Else ' LabelDomainOrWorkgroupName.innerText <> "" and txtQ4aOUName.va lue <> "" ' Convert LabelDomainOrWorkgroupName.innerText to fully qualified domain name strOUname = SelectOUs.value strDomain = "dc=" & LabelDomainOrWorkgroupName.innerText ' The domain name is found on the Q4 tab strDomain = Replace(strDomain,".",",dc=") ' Convert txtQ4aOUName.value to fully qualified domain name strOU = "OU=" & txtQ4aOUName.Value & "," ' The OU name is found on the Q4 tab strOU = Replace(strOU,".",",OU=") ' Convert txtQ4bUserName.value to fully qualified domain name strCNname = "CN=" & txtQ4bUserName ' The user being created is found on the Q4 tab 'Link to the object defined by the provider and the OU and the domain Set objDomain = GetObject(strProvider & strOU & strDomain) If Err.Number <>0 Then errReturn = Err.Number Else ' Err.Number =0 ' Create a new user and return a handle to it Set objOU = objDomain.create(strClass, strCNname) If Err.Number <>0 Then errReturn = Err.Number Else ' Err.Number =0 ' Modify the account name of the user objOU.Put "SAMAccountName", Mid(strCNname,4) 'r emoves cn= from username If Err.Number <>0 Then errReturn = Err.Number Else ' Err.Number =0 ' Commit the change to Active Directory objOU.SetInfo errReturn = Err.Number If Err.Number <>0 Then TabInit.Classname = "TabSelected " Q4bListOUs SelectOUs.value = strOUname Q4bListUsers SelectUsers.value = txtQ4bUserNa me.value TabInit.Classname = "TabUnselect ed" End If ' Err.Number =0 End If ' Err.Number =0 End If ' Err.Number =0 ' Free any memory used by variables Set objOU = Nothing End If ' Err.Number =0 Set objDomain = Nothing End If ' ' LabelDomainOrWorkgroupName.innerText <> "" and txtQ4aOUName. value <> "" ' Place an entry in the applications event log Select Case errReturn Case 0 objShell.LogEvent EVENT_SUCCESS, _ "User " & strCNname & " successfully created in " &_ strProvider & strOU & strDomain Case -1 objShell.LogEvent EVENT_FAILED, _ "User " & strOUname &_ " not created as the domain name was not specifi ed." Case -2 objShell.LogEvent EVENT_FAILED, _ "User not created as the Username was not specif ied." Case "-2147019886" objShell.LogEvent EVENT_FAILED, _ "User " & strOUname &_ " already exists in " & strProvider & strOU & st rDomain &_ " and cannot be created" Case Else objShell.LogEvent EVENT_FAILED, _ "User " & strOUname &_ " could not be created in " & strProvider & strO U &_ strDomain & " error on the play " & errReturn End Select ' errReturn End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 4 c) Deploy a software package to your workstation using a vbs login script '==== (not the Group Policy Object software deployment featu re) '==== Purpose: Join your workstation to the domain specified on the Tab Q3 '==== Inputs: txtQ4cSWPackageLocation.Value '==== Returns: Software installed on workstation '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a SW Package Location has been specified '==== Check that a Username has been specified '==== Get the name of this workstation '==== Get the Win32_Product object from the cimv2 namespace where name = this computer '==== Install the software '==== Free any memory used by variables '==== Place an entry in the applications event log '=============================================================================== ====================== '=============================================================================== ====================== Sub Q4cDeploySWPackage ' Header Section Const ALL_USERS = True Dim objSoftware Dim wmiQuery Dim errReturn Dim strSWLocation ' Check that a SW Package Location has been specified If txtQ4cSWPackageLocation.Value = "" Then errReturn = -1 Else Set objSoftware = objWMIService.Get("Win32_Product") errReturn = objSoftware.Install _ (txtQ4cSWPackageLocation.Value, , ALL_USERS) Set objSoftware = Nothing End If ' Place an entry in the applications event log If Err.number = 0 Then objShell.LogEvent EVENT_SUCCESS, _ strSWLocation & " successfully deployed" Else objShell.LogEvent EVENT_FAILED, _ strSWLocation & " could not be deployed" &_ " error on the play " & Err.Number End If End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Question5Refresh '==== Purpose: To list all the scheduled jobs ontoTabQ5 '==== Inputs: None '==== Returns: Displays the scheduled jobs onto TabQ5 '==== Pseudo code '==== Clear the list of scheduled jobs on TabQ5 '==== Get the collection of scheduled jobs from the Win32_ScheduledJob service in the WMI services '==== Change the size of the list of scheduled tasks so that you can v iew them all '==== Cycle through the collection of scheduled jobs '==== And add it to the selection list '==== Free any memory used by variables '=============================================================================== ====================== '=============================================================================== ====================== Sub Question5Refresh ' Header Section Dim ColScheduledJobs Dim objJob Dim objOption ' Clear the list of scheduled jobs on TabQ5 For Each objOption in SelectTasks.options objOption.RemoveNode Next 'objOption ' Get the collection of scheduled jobs from the Win32_ScheduledJob service in th e WMI services Set ColScheduledJobs = objWMIService.ExecQuery _ ("Select * From Win32_ScheduledJob") ' Change the size of the list of scheduled tasks so that you can view them all SelectTasks.size = ColScheduledJobs.count + 1 ' Cycle through the collection of scheduled jobs For Each objJob in ColScheduledJobs ' A Select element in HTML is made up of a collection of Option elements ' An option element has a number of attributes. We will use two of the attributes - Text and Value ' The Text attribute is what will be displayed, while the Value attribute is the part ' that is used to process what is to be done ' And add it to the selection list set objOption = document.createElement("option") objOption.text = objJob.JobId & " " & objJob.Command objOption.value = objJob.JobId SelectTasks.add(objOption) ' Debug AddToInitLog "Q5_Tasks: " & objJob.JobId & " " & objJob.Command Next 'objJob ' Free any memory used by variables Set ColScheduledJobs = Nothing ' Adjust the html elements so that the event log is in the correct place on the screen End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 5 a) Schedule a task of your choice on your local PC '==== This subroutine is run when we press the btnQ5aScheduleTask butt on '==== Purpose: To schedule a job that is defined on TabQ5 '==== Inputs: txtQ5aTaskName.value The name of the task to be scheduled '==== txtQ5aStartTime.value The time that we want the task t o start '==== txtQ5aFrequency.value The value that the chosen radio button of radQ5aFrequency (daily, monthly or once only) '==== radQ5aFreqDaily, radQ5aFreqMonthly and radQ5aFre qOnce modify the value '==== txtQ5aDaily.value A value that adds the value of t he chkQ5aMonday to chkQ5aSunday checkboxes '==== chkQ5aMonday_onclick to chkQ5aSunday_onclick mod ify the value of txtQ5aDaily.value '==== txtQ5aDayOfMonth.value The day of the month that we wan t our scheduled task to run on if we choose monthly '==== Returns: A new scheduled job is created '==== Places an event in the Application Event Log '==== Pseudo code '==== Get the information from TabQ5 '==== Get the Win32_ScheduledJob object from the WMI service '==== Create the new scheduled job '==== Free any memory used by variables '==== Place an entry in the applications event log '==== List all the scheduled jobs ontoTabQ5 '=============================================================================== ====================== '=============================================================================== ====================== Sub Q5aAddScheduleTask 'Header Section Dim objNewJob Dim objItem Dim strCommand Dim strStartTime Dim boolRunRepeatedly Dim intDaysOfWeek Dim intDaysOfMonth Dim boolInteractWithDesktop Dim intJobid Dim errJobCreated ' Get the information from TabQ5 strCommand = txtQ5aTaskName.value strStartTime = "********" & replace(txtQ5aStartTime.value,":","") &_ ".000000" & fnCurrentTimeZone() ' "YYYYMMDDHHMMSS.MMMMMM(+-)OOO" where "YYYYMMDD" must be replaced by "* *******" ' "(+-)OOO" is the current bias for local time translation ' Multiply the number of hours that your time zone is ahead or behind GM T by 60 ' Add an additional 60 if your time zone is using daylight savings time boolRunRepeatedly = Not (txtQ5aFrequency = "Once") ' If True, a scheduled job runs repeatedly on specific days. The default is False. If txtQ5aFrequency.value = "Daily" Then intDaysOfWeek = cInt(txtQ5aDaily.innerText) ' 1=Monday, 2=Tuesday, 4=Wednesday, 8=Thursday, 16=Friday, 32=Sa turday, 64=Sunday ' txtQ5aDaily.innerText is modified by sub chkQ5aMonday_onclick to sub chkQ5aSunday_onclick Else 'txtQ5aFrequency.value <> "Daily" intDaysOfWeek = 0 End If ''txtQ5aFrequency.value <> "Daily" If txtQ5aFrequency.value = "Monthly" Then intDaysOfMonth = cInt(txtQ5aMonthly.innerText) ' 1=1st, 2=2nd, 4=3rd, 8=4th, 16=5th, ..., 2^(n-1)=nth day of th e month Else 'txtQ5aFrequency.value <> "Monthly" intDaysOfMonth = 0 End If 'txtQ5aFrequency.value <> "Monthly" boolInteractWithDesktop = True ' If your scheduled job starts an interactive program such as Notepad, ' then the InteractWithDeskto property must be set to True or the progra m's screen is not visible. ' The process still appears in the Task Manager even if it does not appe ar on the screen. ' Get the Win32_ScheduledJob object from the WMI service Set objNewJob = objWMIService.Get("Win32_ScheduledJob") ' Create the new scheduled job errJobCreated = objNewJob.Create _ (strCommand, strStartTime, boolRunRepeatedly, _ intDaysOfWeek, intDaysOfMonth, boolInteractWithDesktop, intJobid ) ' Free any memory used by variables Set objNewJob = Nothing ' Place an entry in the applications event log Select Case errJobCreated Case 0 objShell.LogEvent EVENT_SUCCESS, _ "Scheduled Task " & strCommand &_ " successfully created. Job ID = " & intJobid Case 1 objShell.LogEvent EVENT_FAILED, _ "Creation of Scheduled Task " &_ strCommand & " not supported" Case 2 objShell.LogEvent EVENT_FAILED, _ "Scheduled Task " & strCommand &_ " not created. User did not have necessary acces s." Case 8 objShell.LogEvent EVENT_FAILED, _ "Scheduled Task " & strCommand &_ " not created. Interactive process." Case 9 objShell.LogEvent EVENT_FAILED, _ "Scheduled Task " & strCommand &_ " not created. " &_ "The directory path to the service executable fi le cannot be found." Case 21 objShell.LogEvent EVENT_FAILED, _ "Scheduled Task " & strCommand & " not created. " &_ "Invalid parameters have been passed to the serv ice." Case 22 objShell.LogEvent EVENT_FAILED, _ "Scheduled Task " & strCommand & " not created. " &_ "The account that this service runs under is inv alid " &_ "or lacks the permissions to run the service." Case Else objShell.LogEvent EVENT_FAILED, _ "Scheduled Task " & strCommand & " not created. " &_ "Unknown Error." & errJobCreated End select ' List all the scheduled jobs ontoTabQ5 TabInit.Classname = "TabSelected" Question5Refresh TabInit.Classname = "TabUnselected" End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 5 b) Remove the scheduled task on your PC '==== This subroutine is run when we press the btnQ5bRemoveScheduleTas k button '==== Purpose: To remove the schedule a job that is selected on TabQ5 '==== Inputs: SelectTasks.value The name of the selected scheduled job i n the SelectTasks select box '==== Returns: The selected scheduled job is deleted '==== Places an event in the Application Event Log '==== Pseudo code '==== Get the information from TabQ5 '==== Get a link to the sheduled job from the Win32_ScheduledJob objec t in the WMI service '==== that is defined by the selected scheduled job '==== Remember the id and name for the event log '==== Delete the new scheduled job '==== Free any memory used by variables '==== Place an entry in the applications event log '==== List all the scheduled jobs ontoTabQ5 '=============================================================================== ====================== '=============================================================================== ====================== Sub Q5bRemoveScheduleTask 'Header Section Dim objJob Dim strJob Dim errJobDeleted ' Get a link to the sheduled job from the Win32_ScheduledJob object in the WMI s ervice ' that is defined by the selected scheduled job Set objJob = objWMIService.Get _ ("Win32_ScheduledJob.JobID=" & SelectTasks.Value) ' Remember the id and name for the event log StrJob = objJob.JobId & " " & objJob.Command ' Delete the new scheduled job errJobDeleted = objJob.Delete ' Free any memory used by variables Set objJob = Nothing ' Place an entry in the applications event log Select Case errJobDeleted Case 0 objShell.LogEvent EVENT_SUCCESS, _ "Scheduled Task JobID:" & StrJob &_ " successfully deleted" Case 1 objShell.LogEvent EVENT_FAILED, _ "Deletion of Scheduled Task JobID:" &_ StrJob & " not supported" Case 2 objShell.LogEvent EVENT_FAILED, _ "Scheduled Task JobID:" & StrJob &_ " not deleted. User did not have necessary acces s." Case 8 objShell.LogEvent EVENT_FAILED, _ "Scheduled Task JobID:" & StrJob &_ " not deleted. Interactive process." Case 9 objShell.LogEvent EVENT_FAILED, _ "Scheduled Task JobID:" & StrJob & " not deleted. " &_ "The directory path to the service executable file c annot be found." Case 21 objShell.LogEvent EVENT_FAILED, _ "Scheduled Task JobID:" & StrJob & " not deleted. " &_ "Invalid parameters have been passed to the service. " Case 22 objShell.LogEvent EVENT_FAILED, _ "Scheduled Task JobID:" & StrJob & " not deleted. " &_ "The account that this service runs under is invalid " &_ "or lacks the permissions to run the service." Case Else objShell.LogEvent EVENT_FAILED, _ "Scheduled Task JobID:" & StrJob & " not deleted. " &_ "Unknown Error." & errJobCreated End select ' List all the scheduled jobs ontoTabQ5 TabInit.Classname = "TabSelected" Question5Refresh TabInit.Classname = "TabUnselected" End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Q5cRefreshServers '==== This subroutine is run from Question3Refresh '==== Purpose: To list all the servers with a print queue in the domain selected on TabQ5 '==== Inputs: LabelDomainOrWorkgroupName.innerText The name of the domain that we want to select the printer from '==== Returns: The list of servers that have a print queue '==== Pseudo code '==== Clear the server list '==== Make sure that a domain has been specified '==== Create a link to the ADODB connection object '==== Create a link to the ADODB command object '==== Set strDomain to be the fully qualified domain name defined by L abelDomainOrWorkgroupName.innerText '==== Get a collection of servers in the domain that have a print queu e '==== Cycle through the collection of servers in the domain that have a print queue '==== Add the server to the list of servers '==== Adjust the size of the list of servers '==== Free any memory used by variables '==== Initially make sure that no servers are selected '=============================================================================== ====================== '=============================================================================== ====================== Sub Q5cRefreshServers ' Header Section Const ADS_SCOPE_SUBTREE = 2 Dim objConnection Dim objCommand Dim objOption Dim strDomain ' Clear the server list For Each objOption in SelectServers.options objOption.RemoveNode Next 'objOption ' Make sure that a domain has been specified If LabelDomainOrWorkgroupName.innerText <> "" Then ' Create a link to the ADODB connection object Set objConnection = CreateObject("ADODB.Connection") ' Create a link to the ADODB command object Set objCommand = CreateObject("ADODB.Command") objConnection.Provider = "ADsDSOObject" objConnection.Open "Active Directory Provider" ' Set strDomain to be the fully qualified domain name defined by LabelDomainOrWo rkgroupName.innerText strDomain = "dc=" & LabelDomainOrWorkgroupName.innerText strDomain = Replace(strDomain,".",",dc=") ' Get a collection of servers in the domain that have a print queue Set objCommand.ActiveConnection = objConnection objCommand.CommandText = "Select serverName, printerName, driver Name, portName, location " &_ "from 'LDAP://" & strDomain &_ "' where objectClass='printQueue'" objCommand.Properties("Page Size") = 1000 objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE Set objPrinterRecordSet = objCommand.Execute objPrinterRecordSet.MoveFirst SelectServers.size = 0 ' Cycle through the collection of servers in the domain that have a print queue Do Until objPrinterRecordSet.EOF ' Add the server to the list of servers SelectServers.size = SelectServers.size + 1 Set objOption = document.createElement("option") objOption.text = objPrinterRecordSet.Fields("serverName" ).Value objOption.value = objPrinterRecordSet.Fields("serverName ").Value SelectServers.add(objOption) SelectServers.value = objPrinterRecordSet.Fields("server Name").Value ' Debug AddToInitLog "Q5c_Servers: " & objPrinterRecordSet.Field s("serverName").Value objPrinterRecordSet.MoveNext Loop 'Until objPrinterRecordSet.EOF ' Adjust the size of the list of servers If SelectServers.size < 2 Then SelectServers.size = 2 Else SelectServers.value = "" If SelectServers.size > 10 Then SelectServers.size = 10 End If End If ' Free any memory used by variables ' objRecordSet.close ' Set objRecordSet = Nothing Set objCommand = Nothing Set objConnection = Nothing End If 'LabelDomainOrWorkgroupName.innerText <> "" Q5cRefreshNetworkPrinters End Sub 'Q5cRefreshServers '=============================================================================== ====================== '=============================================================================== ====================== '==== Q5cRefreshNetworkPrinters '==== This subroutine is run when we choose a server in SelectServers '==== and also after Q5cRefreshServers is run '==== Purpose: To install the Network printer that is seleced on TabQ5 as a local printer '==== Inputs: SelectTasks.value The name of the selected scheduled job i n the SelectTasks select box '==== Returns: The selected scheduled job is deleted '==== Pseudo code '==== Clear the server list '==== Check that a server has been selected '==== Use the recordset created in SelectServers which has the collect ion of printer names and properties '==== Cycle through the collection of printers '==== Find the ones whose server name is SelectServers.value '==== Add the printername to the list of printer names '==== Adjust the size of the list of Printers '==== If there is one printer on the server, then select it, '==== If there are 2 or more printers in the server, then make sure th at no printernames are selected '==== Place information about selected printer into "Network Printer I nformation" '=============================================================================== ====================== '=============================================================================== ====================== Sub Q5cRefreshNetworkPrinters ' Header Section Dim objOption ' Clear the server list For Each objOption in SelectNetworkPrinters.options objOption.RemoveNode Next 'objOption ' Check that a server has been selected If SelectServers.value <> "" Then ' If there are servers in the SelectServer list, then objPrinterRecordSet has al ready has the collection of printers ' objPrinterRecordSet was populated in the procedure Q5cRefreshServers objPrinterRecordSet.MoveFirst SelectNetworkPrinters.size = 0 ' Adjust the size of the list of Printers ' Cycle through the collection of printer names in the domain that have a print queue Do Until objPrinterRecordSet.EOF ' Find the ones whose server name is SelectServers.value If objPrinterRecordSet.Fields("serverName").Value = Sele ctServers.value Then ' Add the printername to the list of printer names SelectNetworkPrinters.size = SelectNetworkPrinte rs.size + 1 ' Adjust the size of the list of Printers set objOption = document.createElement("option") objOption.text = objPrinterRecordSet.Fields("pri nterName").Value objOption.value = objPrinterRecordSet.Fields("pr interName").Value SelectNetworkPrinters.add(objOption) ' If there is one printer on the server, then select it SelectNetworkPrinters.value = objPrinterRecordSe t.Fields("printerName").Value ' Debug AddToInitLog "Q5c_Network_Printers: " & objPrint erRecordSet.Fields("printerName").Value End If objPrinterRecordSet.MoveNext Loop ' Until objPrinterRecordSet.EOF ' Adjust the size of the list of Printers If SelectNetworkPrinters.size < 2 Then SelectNetworkPrinters.size = 2 Else ' If there are 2 or more printers in the server, then make sure that no printern ames are selected SelectNetworkPrinters.value="" If SelectNetworkPrinters.size > 10 Then SelectNetworkPrinters.size = 10 End If End If End If 'SelectServers.value <> "" ' Place information about selected printer into "Network Printer Information" Q5cSelectPrinter End Sub 'Q5cRefreshPrinters '=============================================================================== ====================== '=============================================================================== ====================== '==== Q5cSelectPrinter '==== This subroutine is run when we choose a printer in SelectNetwork Printers '==== Purpose: To place the values of the selected printer into "Networ k Printer Information" '==== Inputs: SelectNetworkPrinters.value The name of the selected printer in SelectNetworkPrinters select box '==== Returns: DriverName, portName, DeviceID and location '==== Pseudo code '==== Check that a printer has been selected '==== Use the recordset created in SelectServers which has the collect ion of printer names and properties '==== Cycle through the collection of printer names in the domain that have a print queue '==== Find the ones whose server name is SelectServers.value and prin ter name is SelectNetworkPrinters.value '==== Add the driver name to the list of driver names '==== Add the port name to the list of port names '==== Add the DeviceID to the list of DeviceIDs '==== Add the location to the list of locations (and prevent "Null" fr om appearing in the list) '=============================================================================== ====================== '=============================================================================== ====================== Sub Q5cSelectPrinter ' Header Section ' Check that a server has been selected If SelectNetworkPrinters.value <> "" Then ' Use the recordset created in SelectServers which has the collection of printer names and properties objPrinterRecordSet.MoveFirst ' Cycle through the collection of printer names in the domain that have a print queue Do Until objPrinterRecordSet.EOF ' Find the ones whose server name is SelectServers.value and printer name is Se lectNetworkPrinters.value If objPrinterRecordSet.Fields("serverName").Value = Sele ctServers.value _ And objPrinterRecordSet.Fields("printerName").Value = Se lectNetworkPrinters.value Then ' Add the driver name to the list of driver names txtQ5cDriverName.Value = objPrinterRecordSet.Fie lds("driverName").Value ' Add the port name to the list of port names txtQ5cPortName.Value = join(objPrinterRecordSet. Fields("portName").Value) ' Add the DeviceID to the list of DeviceIDs txtQ5cDeviceID.Value = SelectNetworkPrinters.val ue ' Add the location to the list of locations (and prevent "Null" from appearing i n the list) If IsNull(objPrinterRecordSet.Fields("location") .Value) Then txtQ5cLocation.Value = "" 'Prevent "Null" from appearing in the list Else txtQ5cLocation.Value = objPrinterRecordS et.Fields("location").Value End If ' Debug AddToInitLog "Q5c_Select_Network_Printer: " & Se lectNetworkPrinters.value &_ ", Port: " & join(objPrinterRecordSet.Fi elds("portName").Value) End If 'serverName and printerName are the correct valu e objPrinterRecordSet.MoveNext Loop ' Until objRecordSet.EOF End If 'SelectServers.value <> "" End Sub 'Q5cRefreshPrinters '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 5 c) Install a Network printer as a local printer '==== This subroutine is run when we press the btnQ5cInstallNetworkPri nter button '==== Purpose: To install the Network printer that is seleced on TabQ5 as a local printer '==== Inputs: SelectServers.value The name of the selected server in the S electServers select box '==== SelectNetworkPrinters.value The name of the selected printer in the SelectNetworkPrinters select box '==== Returns: The network printer is installed as a local printer '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a server has been selected '==== Check that a printer has been selected '==== Create a Printer Port based on txtQ5cPortName.value '==== Create a local printer that prints to the new port based on the information in "Network Printer Information" '==== Place an entry in the applications event log '==== Refresh the list of local printers '=============================================================================== ====================== '=============================================================================== ====================== Sub Q5cInstallNetworkPrinter ' Header Section On Error Resume Next Dim objNewPort Dim objPrinter Dim errReturn ' Check that a server has been selected If SelectServers.value = "" Then errReturn = -1 ' Check that a printer has been selected ElseIf SelectNetworkPrinters.value = "" Then errReturn = -2 Else 'SelectServers.value <> "" and SelectNetworkPrinters.value <> "" ' Create a Printer Port based on txtQ5cPortName.value Set objNewPort = objWMIService.Get _ ("Win32_TCPIPPrinterPort").SpawnInstance_ objNewPort.Name = txtQ5cPortName.Value objNewPort.Protocol = 1 ' The next line depends on the port name having a form IP_xx.xx. xx.xx ' We create the host address by stripping the first three charac ters off the port name objNewPort.HostAddress = mid(txtQ5cPortName.Value,4) objNewPort.PortNumber = "9999" objNewPort.SNMPEnabled = False objNewPort.Put_ ' Create a local printer that prints to the new port based on the information in "Network Printer Information" Set objPrinter = objWMIService.Get("Win32_Printer").SpawnInstanc e_ objPrinter.DriverName = txtQ5cDriverName.Value objPrinter.PortName = txtQ5cPortName.Value objPrinter.DeviceID = txtQ5cDeviceID.Value objPrinter.Location = txtQ5cLocation.Value objPrinter.Network = False objPrinter.Shared = False objPrinter.Put_' Create a link to the wScript network object objPrinter.SetDefaultPrinter() errReturn = err.number End If ' Place an entry in the applications event log Select Case errReturn Case 0 objShell.LogEvent EVENT_SUCCESS, _ "Network Printer connected. \\" &_ SelectServers.value & "\" & SelectNetwor kPrinters.value Case -1 objShell.LogEvent EVENT_FAILED, _ "Network Printer not connected. Server not specified ." Case -2 objShell.LogEvent EVENT_FAILED, _ "Network Printer not connected. Printer not specifie d." Case -2147023095 objShell.LogEvent EVENT_FAILED, _ "Network Printer not connected. " &_ "Check Server & Printer names. \\" &_ SelectServers.value & "\" & SelectNetworkPrinter s.value Case else objShell.LogEvent EVENT_FAILED, _ "Network Printer not connected. " &_ "Unknown error " & errReturn &_ ". \\" & SelectServers.value & "\" &_ SelectNetworkPrinters.value End select UpdateEventLog ' Refresh the list of local printers TabInit.Classname = "TabSelected" Q5cRefreshLocalPrinters TabInit.Classname = "TabUnselected" End Sub ' Q5cInstallNetworkPrinter '=============================================================================== ====================== '=============================================================================== ====================== '==== Q5cRefreshLocalPrinters '==== This subroutine is run from window_onload, '==== and when we install a network printer as a local printer in Q5cI nstallNetworkPrinter '==== Purpose: To list all the printers that are installed locally '==== Inputs: None '==== Returns: The list of local printers '==== Pseudo code '==== Clear the Local Printer lists '==== Get the collection of installed printers from the Win32_Printer object in the WMI service '==== Adjust the size of the lists '==== Cycle through the collection of installed printers '==== Place the printer name into the list of Local Printer Names '==== Place the location into the list of Local Printer Locations (and prevent "Null" from appearing in the list) '==== Place the port name into the list of Local Printer PortNames '==== Place the printer default flag into the list of Local Printer de fault flags '==== If there is one printer, then select it '==== If there is more than one printer, then select nothing '==== Free any memory used by variables '==== List any PrintJobs on the selected local printer '=============================================================================== ====================== '=============================================================================== ====================== Sub Q5cRefreshLocalPrinters Dim objOption Dim intNumPrinters Dim colInstalledPrinters Dim objPrinter ' Clear the Local Printer lists For Each objOption in SelectLocalPrintersName.options objOption.RemoveNode Next 'objOption For Each objOption in SelectLocalPrintersLocation.options objOption.RemoveNode Next 'objOption For Each objOption in SelectLocalPrintersPort.options objOption.RemoveNode Next 'objOption For Each objOption in SelectLocalPrintersDefault.options objOption.RemoveNode Next 'objOption ' Get the collection of installed printers from the Win32_Printer object in the WMI service Set colInstalledPrinters = objWMIService.ExecQuery _ ("Select * from Win32_Printer") ' Adjust the size of the lists intNumPrinters = colInstalledPrinters.Count If intNumPrinters < 2 Then intNumPrinters = 2 If intNumPrinters > 5 Then intNumPrinters = 5 SelectLocalPrintersName.size = intNumPrinters SelectLocalPrintersLocation.size = intNumPrinters SelectLocalPrintersPort.size = intNumPrinters SelectLocalPrintersDefault.size = intNumPrinters ' Cycle through the collection of installed printers For Each objPrinter in colInstalledPrinters ' Place the printer name into the list of Local Printer Names set objOption = document.createElement("option") objOption.text = objPrinter.Name objOption.value = objPrinter.DeviceID SelectLocalPrintersName.add(objOption) ' Place the location into the list of Local Printer Locations (and prevent "Null " from appearing in the list) set objOption = document.createElement("option") If isNull(objPrinter.Location) Then objOption.text = "" Else objOption.text = objPrinter.Location End If objOption.value = objPrinter.DeviceID SelectLocalPrintersLocation.add(objOption) ' Place the port name into the list of Local Printer PortNames set objOption = document.createElement("option") objOption.text = objPrinter.PortName objOption.value = objPrinter.DeviceID SelectLocalPrintersPort.add(objOption) ' Place the printer default flag into the list of Local Printer default flags set objOption = document.createElement("option") objOption.text = objPrinter.Default objOption.value = objPrinter.DeviceID SelectLocalPrintersDefault.add(objOption) ' Debug AddToInitLog "Q5d_Local_Printers: " & objPrinter.Name ' If there is one printer, then select it SelectLocalPrintersName.value = objPrinter.DeviceID SelectLocalPrintersLocation.value = objPrinter.DeviceID SelectLocalPrintersPort.value = objPrinter.DeviceID SelectLocalPrintersDefault.value = objPrinter.DeviceID Next ' objPrinter If colInstalledPrinters.Count <> 1 Then ' If there is more than one printer, then select nothing SelectLocalPrintersName.value = "" SelectLocalPrintersLocation.value = "" SelectLocalPrintersPort.value = "" SelectLocalPrintersDefault.value = "" End If ' Free any memory used by variables Set colInstalledPrinters = Nothing ' List any PrintJobs on the selected local printer Q5dListLocalPrinterJobs End Sub 'Q5cRefreshLocalPrinters '=============================================================================== ====================== '=============================================================================== ====================== '==== Q5dListLocalPrinterJobs '==== This subroutine is run when we choose a printer in SelectLocalPr inters '==== Note that it is not real time. It only lists the print jobs on l ocal printers at the time it was called. '==== Purpose: List the printer jobs that are current on the printer se lected in SelectLocalPrinters '==== Inputs: SelectLocalPrintersName The name of the printer that we are list ing the jobs for '==== Returns: The PrintJobs in the selected local printer are listed '==== Pseudo code '==== Clear the printer job lists '==== Check that a local printer has been selected '==== Get a collection of printer jobs from the Win32_PrintJob object in the WMI service '==== Cycle through the collection of printer jobs '==== Find the print jobs from the printer selected in SelectLocalPrin tersName '==== Add the Document to the list of Documents '==== Add the JobStatus to the list of JobStatuses '==== Add the JobSize to the list of JobSizes '==== Add the TimeSubmitted to the list of TimesSubmitted '==== Adjust the size of the lists '==== Select no PrintJobs '==== Free any memory used by variables '=============================================================================== ====================== '=============================================================================== ====================== Sub Q5dListLocalPrinterJobs ' Header Section Dim objOption Dim colPrintJobs Dim objPrintJob ' Clear the print job lists For Each objOption in SelectPrintJobDocument.options objOption.RemoveNode Next 'objOption For Each objOption in SelectPrintJobJobStatus.options objOption.RemoveNode Next 'objOption For Each objOption in SelectPrintJobSize.options objOption.RemoveNode Next 'objOption For Each objOption in SelectPrintJobTimeSubmitted.options objOption.RemoveNode Next 'objOption ' Check that a local printer has been selected If SelectLocalPrintersName.value <> "" Then ' Get a collection of printer jobs from the Win32_PrintJob object in the WMI ser vice Set colPrintJobs = objWMIService.ExecQuery _ ("Select * from Win32_PrintJob") ' Adjust the size of the lists SelectPrintJobDocument.size = 0 SelectPrintJobJobStatus.size = 0 SelectPrintJobSize.size = 0 SelectPrintJobTimeSubmitted.size = 0 ' Cycle through the collection of printer jobs For Each objPrintJob in colPrintJobs ' Find the print jobs from the printer selected in SelectLocalPrintersName ' objPrintJob.name is a combination of the name of the p rinter where the job is queued and the ID number assigned to the print job separ ated by a comma ' We are only interested in the part before the comma, s o we turn objPrintJob.name into an array, and look at the first element ' If it is the same as the name of the printer that we h ave selected in SelectLocalPrintersName, then place the print job in our print j ob lists If split(objPrintJob.name,",")(0) = SelectLocalPrintersN ame.value Then ' Adjust the size of the lists SelectPrintJobDocument.size = SelectPrintJobDoc ument.size + 1 SelectPrintJobJobStatus.size = SelectPrintJobJo bStatus.size + 1 SelectPrintJobSize.size = SelectPrintJobSize.si ze + 1 SelectPrintJobTimeSubmitted.size = SelectPrintJ obTimeSubmitted.size + 1 ' Add the Document to the list of Documents set objOption = document.createElement("option") objOption.text = objPrintJob.Document objOption.value = objPrintJob.JobId SelectPrintJobDocument.add(objOption) ' Add the JobStatus to the list of JobStatuses set objOption = document.createElement("option") objOption.text = objPrintJob.JobStatus objOption.value = objPrintJob.JobId SelectPrintJobJobStatus.add(objOption) ' Add the JobSize to the list of JobSizes set objOption = document.createElement("option") objOption.text = objPrintJob.Size objOption.value = objPrintJob.JobId SelectPrintJobSize.add(objOption) ' Add the TimeSubmitted to the list of TimesSubmitted set objOption = document.createElement("option") objOption.text = objPrintJob.TimeSubmitted objOption.value = objPrintJob.JobId SelectPrintJobTimeSubmitted.add(objOption) ' Debug AddToInitLog "Q5d_Printer_Queue: " & objPrintJob .Document End If Next 'objPrintJob ' Adjust the size of the lists If SelectPrintJobDocument.size < 2 Then SelectPrintJobDocument.size = 2 SelectPrintJobJobStatus.size = 2 SelectPrintJobSize.size = 2 SelectPrintJobTimeSubmitted.size = 2 End If ' Select no PrintJobs SelectPrintJobDocument.value = "" SelectPrintJobJobStatus.value = "" SelectPrintJobSize.value = "" SelectPrintJobTimeSubmitted.value = "" ' Free any memory used by variables Set colPrintJobs = Nothing End If 'SelectServers.value <> "" and SelectNetworkPrinters.value <> "" End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 5 d) Purge/Clear the printer queue '==== This subroutine is run when we press the btnQ5dPurgePrinterQueue button '==== Purpose: To purge the Local printer queue that is seleced on TabQ 5 '==== Inputs: SelectLocalPrintersName.value The name of the selected printer in the SelectLocalPrintersName select box '==== Returns: The local printer queue is purged '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a local printer has been selected '==== Create a link to the Win32_Printer object from the WMI service '==== where the printer deviceID is the one we have selected i n SelectLocalPrintersName '==== Cycle through the collection of printers '==== And cancel all jobs from each one '==== Free any memory used by variables '==== Place an entry in the applications event log '==== List all the print jobs on the selected local printer on TabQ5 '=============================================================================== ====================== '=============================================================================== ====================== Sub Q5dPurgePrinterQueue 'Header Section Dim colInstalledPrinters Dim objPrinter Dim errReturn ' Check that a local printer has been selected If SelectLocalPrintersName.value = "" Then errReturn = -2 Else 'SelectServers.value <> "" and SelectNetworkPrinters.value <> "" ' Create a link to the Win32_Printer object from the WMI service ' where the printer deviceID is the one we have selected in SelectLocalPri ntersName Set colInstalledPrinters = objWMIService.ExecQuery _ ("Select * from Win32_Printer Where DeviceID = '" & SelectLo calPrintersName.value & "'") ' Cycle through the collection of printers For Each objPrinter in colInstalledPrinters ' And cancel all jobs from each one objPrinter.CancelAllJobs() Next ' Free any memory used by variables Set colInstalledPrinters = Nothing End If 'SelectServers.value <> "" and SelectNetworkPrinters.value <> "" ' Place an entry in the applications event log Select Case errReturn Case 0 objShell.LogEvent EVENT_SUCCESS, _ "Network Printer purged. \\" &_ SelectServers.value & "\" &_ SelectNetworkPrinters.value Case -1 objShell.LogEvent EVENT_FAILED, _ "Network Printer not purged. Server not specified." Case -2 objShell.LogEvent EVENT_FAILED, _ "Network Printer not purged. Printer not specified." Case -2147023095 objShell.LogEvent EVENT_FAILED, _ "Network Printer not purged. " &_ "Check Server & Printer names. \\" &_ SelectServers.value & "\" & SelectNetworkPrinter s.value Case else objShell.LogEvent EVENT_FAILED, _ "Network Printer not purged. Unknown error " &_ errReturn & ". \\" & SelectServers.value &_ "\" & SelectNetworkPrinters.value End select UpdateEventLog ' List all the print jobs on the selected local printer on TabQ5 Q5dListLocalPrinterJobs End Sub ' Q5dPurgePrinterQueue '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 6 a) Delegate control of your OU to your user account '==== This subroutine is run when we press the btnQ6aDelegateControl b utton '==== Purpose: To delegate control of the selected OU to the selected u ser '==== Inputs: LabelDomainOrWorkgroupName.innerText The name of the domain t hat the computer is logged into '==== SelectOUs.value The name of the OU that we want to deleg ate contol of '==== SelectUsers.value The name of the user that we wan t to delegate contol to '==== Returns: The OU has its control delegated to the user '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a domain has been selected '==== Check that an OU has been selected '==== Check that a user has been selected '==== Create a link to the domain object from the LDAP provider define d by the domain name and the OU name '==== Delegate control of the OU to the user '==== Place an entry in the applications event log '=============================================================================== ====================== '=============================================================================== ====================== Sub Q6aDelegateControlOfOU ' Header Section On Error Resume Next Const ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &H5 Const ADS_FLAG_OBJECT_TYPE_PRESENT = &H1 Const ADS_FLAG_INHERITED_OBJECT_TYPE_PRESENT = &H2 Const ADS_RIGHT_DS_CONTROL_ACCESS = &H100 Const ADS_ACEFLAG_INHERIT_ACE = &H2 Dim errReturn Dim strProvider Dim strDomain Dim strOUname Dim objSdUtil Dim objSD Dim objDACL Dim objAce ' Check that a domain has been selected If LabelDomainOrWorkgroupName.innerText = "" Then errReturn = -1 ' Check that an OU has been selected ElseIf SelectOUs.value = "" Then errReturn = -2 ' Check that a user has been selected ElseIf SelectUsers.value = "" Then errReturn = -3 Else ' Create a link to the domain object from the LDAP provider defined by the domai n name and the OU name strProvider = "LDAP://" ' Lightweight Directory Access P rotocol provider ' Domain comes from the Q6 tab strDomain = "dc=" & LabelDomainOrWorkgroupName.innerText ' Convert the Domain to the fully qualified form strDomain = Replace(strDomain,".",",dc=") ' The Organisational Unit comes from the Q6 tab strOUname = "OU=" & SelectOUs.value Set objSdUtil = GetObject(strProvider & strOU & strDomain) ' Delegate control of the OU to the user Set objSD = objSdUtil.Get("ntSecurityDescriptor") Set objDACL = objSD.DiscretionaryACL Set objAce = CreateObject("AccessControlEntry") objAce.Trustee = SelectUsers.text objAce.AceFlags = ADS_ACEFLAG_INHERIT_ACE objAce.AceType = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT objAce.Flags = ADS_FLAG_OBJECT_TYPE_PRESENT OR _ ADS_FLAG_INHERITED_OBJECT_TYPE_PRESENT objAce.ObjectType = "{00299570-246d-11d0-a768-00aa006e0529}" objACE.InheritedObjectType = "{BF967ABA-0DE6-11D0-A285-00AA00304 9E2}" objAce.AccessMask = ADS_RIGHT_DS_CONTROL_ACCESS objDacl.AddAce objAce objSD.DiscretionaryAcl = objDacl objSDUtil.Put "ntSecurityDescriptor", Array(objSD) objSDUtil.SetInfo errReturn = err.number End If ' Place an entry in the applications event log Select Case errReturn Case 0 objShell.LogEvent EVENT_SUCCESS, _ "Control of OU " & strOUname & " delegated to " &_ SelectUsers.value Case -1 objShell.LogEvent EVENT_FAILED, _ "Control of OU not delegated. Domain not specified." Case -2 objShell.LogEvent EVENT_FAILED, _ "Control of OU not delegated. OU not specified." Case -3 objShell.LogEvent EVENT_FAILED, _ "Control of OU " & SelectOUs.value &_ " not delegated. User not specified." Case else objShell.LogEvent EVENT_FAILED, _ "Control of OU " & SelectOUs.value &_ " not delegated. Unknown error " & errReturn End select UpdateEventLog End Sub ' Q6aDelegateControlOfOU '=============================================================================== ====================== '=============================================================================== ====================== '==== Q6bListLocalGroups '==== This subroutine is called from Window_OnLoad '==== Purpose: To list the local groups that are on the computer '==== Inputs: None '==== Returns: The list of local groups is placed into SelectQ6bListGro ups '==== The Administrator group is selected by default '==== Pseudo code '==== Clear the SelectQ6bListGroups list '==== Get the collection of local groups '==== Cycle through the collection of local groups '==== Place the local group into the list of local groups '==== Free any memory used by variables '==== Select the Administrators local group as default '==== List the users in the selected local group '=============================================================================== ====================== '=============================================================================== ====================== Sub Q6bListLocalGroups ' Header Section Dim objOption Dim strComputer Dim colGroups Dim objGroup ' Clear the SelectQ6bListGroups list For Each objOption in SelectLocalGroups.options objOption.RemoveNode Next 'objOption ' Get the collection of local groups strComputer = "." Set colGroups = GetObject("WinNT://" & strComputer & "") colGroups.Filter = Array("group") SelectLocalGroups.size = 0 ' Cycle through the collection of local groups For Each objGroup In colGroups ' Place the local group into the list of local groups SelectLocalGroups.size = SelectLocalGroups.size + 1 Set objOption = Document.createElement("OPTION") objOption.Text = objGroup.Name objOption.Value = objGroup.Name SelectLocalGroups.Add(objOption) ' Debug AddToInitLog "Q6b_Groups: " & objGroup.Name Next ' objGroup If SelectLocalGroups.size < 2 Then SelectLocalGroups.size = 2 ' Free any memory used by variables Set colGroups = Nothing ' Select the Administrators local group as default SelectLocalGroups.value = "Administrators" ' List the users in the selected local group Q6bListUsersInLocalGroup End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Q6bListUsersInLocalGroup '==== This subroutine is called from Q6bListLocalGroups '==== Purpose: To list the users that are in the local group that is se lected '==== Inputs: SelectQ6bListGroups.value '==== Returns: The list of users that are in the local group that is se lected is placed into SelectQ6bListUsers '==== No user is selected by default '==== Pseudo code '==== Clear the SelectQ6bListUsers list '==== Check that a local group has been selected '==== Get a link to the local group that we have selected '==== Cycle through the collection of users in the selected local grou p '==== Place the username into the list of usernames '==== Adjust the size of the list of usernames '==== Free any memory used by variables '==== Select nothing as default '=============================================================================== ====================== '=============================================================================== ====================== Sub Q6bListUsersInLocalGroup ' Header Section Dim objOption Dim strComputer Dim objGroup Dim objUser ' Clear the SelectQ6bListUsers list For Each objOption in SelectUsersInLocalGroups.options objOption.RemoveNode Next 'objOption ' Check that a local group has been selected If SelectLocalGroups.value <> "" Then ' Get a link to the local group that we have selected strComputer = "." Set objGroup = GetObject("WinNT://"& strComputer &"/" &_ SelectLocalGroups.value) ' Adjust the size of the list of usernames SelectUsersInLocalGroups.size = 0 ' Cycle through the collection of users in the selected local group For Each objUser in objGroup.Members ' Adjust the size of the list of usernames SelectUsersInLocalGroups.size = SelectUsersInLocalGroup s.size + 1 ' Place the username into the list of usernames Set objOption = Document.createElement("OPTION") objOption.Text = objUser.Name objOption.Value = objUser.Name SelectUsersInLocalGroups.Add(objOption) ' Debug AddToInitLog "Q6b_Local_Users: " & objUser.Name Next ' objGroup ' Adjust the size of the list of usernames If SelectUsersInLocalGroups.size < 2 Then SelectUsersInLocalGrou ps.size = 2 ' Free any memory used by variables Set objGroup = Nothing End If ' SelectQ6bListGroups.value <> "" ' Select nothing as default SelectUsersInLocalGroups.value = "" End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 6 b) Assign your Domain account to your local Admins group '==== This subroutine is called when btnQ6bAssignAccountToLocalGroup i s clicked '==== Purpose: To assign the selected domain user to the selected local group '==== Inputs: LabelDomainOrWorkgroupName.innerText Domain name '==== txtQ6aOUName.value OU name '==== SelectUsers.value Dmain User name '==== SelectQ6bListGroups.value Local Group name '==== Returns: The selected domain user is assigned to the selected loc al group '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a domain has been specified '==== Check that an OU has been selected '==== Check that a domain user has been selected '==== Check that a local group has been selected '==== Get a link to the local group that we have selected '==== Assign the selected domain user to the selected local group '==== Free any memory used by variables '==== Place an entry in the applications event log '=============================================================================== ====================== '=============================================================================== ====================== Sub Q6bAssignUserToGroup ' Header section Dim strComputer Dim objGroup Dim objUser ' Check that a domain has been specified If LabelDomainOrWorkgroupName.innerText = "" Then errReturn = -1 ' Check that a domain user has been selected ElseIf SelectUsers.value = "" Then errReturn = -3 ' Check that a local group has been selected ElseIf SelectQ6bListGroups.value = "" Then errReturn = -4 Else ' Get a link to the local group that we have selected strComputer = "." Set objGroup = GetObject("WinNT://"& strComputer & "/" &_ SelectQ6bListGroups.value) ' Assign the selected domain user to the selected local group on error resume next 'We want to put the error value into the ap plication event log group.Add "WinNT://"& LabelDomainOrWorkgroupName.innerText & "/" &_ SelectUsers.text &"" errReturn = err.number ' Free any memory used by variables Set objGroup = Nothing End If ' SelectQ6bListGroups.value <> "" ' Place an entry in the applications event log Select Case errReturn Case 0 objShell.LogEvent EVENT_SUCCESS, _ "Domain account //"& LabelDomainOrWorkgroupName.inne rText &_ "/" & SelectUsers.value &_ " Assigned to " & SelectUsers.value &"" Case -1 objShell.LogEvent EVENT_FAILED, _ "Domain account not assigned. Domain not specified." Case -2 objShell.LogEvent EVENT_FAILED, _ "Domain account not assigned. OU not specified." Case -3 objShell.LogEvent EVENT_FAILED, _ "Domain account not assigned. User not specified." Case -4 objShell.LogEvent EVENT_FAILED, _ "Domain account not assigned. Local group not specif ied." Case else objShell.LogEvent EVENT_FAILED, _ "Domain account not assigned. Unknown error " & errR eturn End select UpdateEventLog End Sub 'Q6bAssignUserToGroup '=============================================================================== ====================== '=============================================================================== ====================== '==== Question 6 c) Delete your domain user account '==== This subroutine is run when we press the btnQ6cDeleteDomainUserA ccount button '==== Purpose: To delete the selected domain user account '==== Inputs: LabelDomainOrWorkgroupName.innerText The name of the domain t hat the computer is logged into '==== SelectOUs.value The name of the OU that the user we want to delete '==== SelectUsers.value The name of the user that we wan t to delete '==== Returns: The domain user account is deleted '==== Places an event in the Application Event Log '==== Pseudo code '==== Check that a domain has been selected '==== Check that an OU has been selected '==== Check that a user has been selected '==== Create a link to the domain object from the LDAP provider define d by the domain name and the OU name '==== Delete the domain user account '==== Free any memory used by variables '==== Place an entry in the applications event log '=============================================================================== ====================== '=============================================================================== ====================== Sub Q6cDeleteDomainUserAccount ' Header Section Dim strProvider Dim strDomain Dim strOU Dim strUserName ' Check that a domain has been selected If LabelDomainOrWorkgroupName.innerText = "" Then errReturn = -1 ' Check that a user has been selected ElseIf SelectUsers.value = "" Then errReturn = -3 Else ' LabelDomainOrWorkgroupName.innerText <> "" and txtQ6aOUName.value <> "" and txtQ6aUserName.value <> "" ' Create a link to the domain object from the LDAP provider defined by the domai n name and the OU name ' strProvider = "LDAP://" ' Lightweight Directory Access P rotocol provider ' Domain comes from the Q6 tab ' strDomain = "dc=" & LabelDomainOrWorkgroupName.innerText ' Convert the Domain to the fully qualified form ' strDomain = Replace(strDomain,".",",dc=") ' The Organisational Unit comes from the Q6 tab ' strOU = "ou=" & txtQ6aOUName.value ' The user from the Q6 tab ' strUserName = "cn=" & txtQ6aUserName.value ' Set objUser = GetObject(strProvider & strOU & strDomain) ' Note that strProvider, strOU and strDomain are already in SelectUserOUs.Text ' and strUserName is in SelectUsers.Text Set objUser = GetObject(SelectUserOUs.Text) ' Delete the domain user account objUser.delete "User", SelectUsers.Text ' Free any memory used by variables Set objUser = Nothing End If ' DomainName.value <> "" and OUName.value <> "" and UserName.val ue <> "" ' Place an entry in the applications event log Select Case errReturn Case 0 objShell.LogEvent EVENT_SUCCESS, _ "Domain account //"& LabelDomainOrWorkgroupName.inne rText &_ "/" & SelectUsers.value &_ " deleted." Case -1 objShell.LogEvent EVENT_FAILED, _ "Domain account not deleted. Domain not specified." Case -2 objShell.LogEvent EVENT_FAILED, _ "Domain account not deleted. OU not specified." Case -3 objShell.LogEvent EVENT_FAILED, _ "Domain account not deleted. User not specified." Case -4 objShell.LogEvent EVENT_FAILED, _ "Domain account not deleted. Local group not specifi ed." Case else objShell.LogEvent EVENT_FAILED, _ "Domain account not deleted. Unknown error " & errRe turn End select UpdateEventLog End Sub 'Q6cDeleteDomainUserAccount '=============================================================================== ====================== '=============================================================================== ====================== '==== UpdateEventLog '==== Purpose: To update the list of event log events on the screen '==== Inputs: LastTimeWritten '==== Returns: Any event that was placed in the event log after the las t time that this procedure was called '==== is placed in the list of event logs '==== LastTimeWritten is updated to the time of the latest eve nt '==== Pseudo code '==== Get the collection of application logged events from the Win32_N TLogEvent object '==== that has a time stamp greater than last time '==== Cycle through the list of events '==== Place the event name etc into the event log list '==== LastTimeWritten is updated to the time of the latest event '==== Free any memory used by variables '=============================================================================== ====================== '=============================================================================== ====================== Sub UpdateEventLog() Dim colLoggedEvents Dim objEvent Dim objOption ' Get the collection of application logged events from the Win32_NTLogEvent obje ct that has a time stamp greater than last time Set colLoggedEvents = objWMIService.ExecQuery _ ("Select * from Win32_NTLogEvent " &_ "Where Logfile = 'Application' " &_ "And TimeWritten > '" & LastTimeWritten &"'") ' Cycle through the list of events For Each objEvent in colLoggedEvents EventLogSize = EventLogSize + 1 ' Place the event name etc into the event log list ' A Select element in HTML is made up of a collection of Option elements ' An option element has a number of attributes. We will use two of the attributes - Text and Value ' The Text attribute is what will be displayed, while the Value attribute is the part ' that is used to process what is to be done set objOption = document.createElement("option") objOption.text = objEvent.RecordNumber objOption.value = objEvent.RecordNumber ' This adds the Option element into SelectEventLogRecordNumber SelectEventLogRecordNumber.add(objOption) set objOption = document.createElement("option") objOption.text = objEvent.Type objOption.value = objEvent.RecordNumber SelectEventLogType.add(objOption) ' This adds the Option e lement into SelectEventLogType set objOption = document.createElement("option") objOption.text = mid(objEvent.TimeWritten,7,2) & "/" &_ mid(objEvent.TimeWritten,5,2) & "/" &_ mid(objEvent.TimeWritten,1,4) objOption.value = objEvent.RecordNumber SelectEventLogDate.add(objOption) ' This adds the Option e lement into SelectEventLogDate set objOption = document.createElement("option") objOption.text = mid(objEvent.TimeWritten,9,2) & ":" &_ mid(objEvent.TimeWritten,11,2) & ":" &_ mid(objEvent.TimeWritten,13,2) objOption.value = objEvent.RecordNumber SelectEventLogtime.add(objOption) ' This adds the Option e lement into SelectEventLogtime set objOption = document.createElement("option") objOption.text = objEvent.SourceName objOption.value = objEvent.RecordNumber SelectEventLogSource.add(objOption) ' This adds the Option e lement into SelectEventLogSource ' LastTimeWritten is updated to the time of the latest event If objEvent.TimeWritten > LastTimeWritten Then LastTimeWritten = objEvent.TimeWritten End If SelectEventLogRecordNumber.value = objEvent.RecordNumber SelectEventLogType.value = objEvent.RecordNumber SelectEventLogDate.value = objEvent.RecordNumber SelectEventLogtime.value = objEvent.RecordNumber SelectEventLogSource.value = objEvent.RecordNumber Next ' If there are less than 2 events, set the size of the lists to 2 to get rid of the scroll bars If EventLogSize < 2 Then SelectEventLogRecordNumber.size = 2 SelectEventLogType.size = 2 SelectEventLogDate.size = 2 SelectEventLogtime.size = 2 SelectEventLogSource.size = 2 Else SelectEventLogRecordNumber.size = EventLogSize SelectEventLogType.size = EventLogSize SelectEventLogDate.size = EventLogSize SelectEventLogtime.size = EventLogSize SelectEventLogSource.size = EventLogSize End If ' Free any memory used by variables Set colLoggedEvents = Nothing If EventLogSize > 0 Then UpdateEventLogDescription(SelectEventLogRecordNumber.value) End If End Sub '=============================================================================== ====================== '=============================================================================== ====================== '==== UpdateEventLogDescription '==== Purpose: To place a more detailed record of the event log entry i nto taEventLogDescription '==== Inputs: RecordNumber '==== Returns: a more detailed record of the event log entry into taEve ntLogDescription '==== Pseudo code '==== Get the collection of logged events from the Win32_NTLogEvent ob ject '==== that has a record number that we have specified '==== Cycle through the list of events '==== Build up the description of the logged event '==== Place the description into taEventLogDescription '==== Free any memory used by variables '=============================================================================== ====================== '=============================================================================== ====================== Sub UpdateEventLogDescription(RecordNumber) Dim colEvents Dim objEvent Dim strDescription ' Get the collection of logged events from the Win32_NTLogEvent object that has a record number that we have specified Set colEvents = objWMIService.ExecQuery _ ("Select * from Win32_NTLogEvent where RecordNumber=" & RecordNumber ) ' Cycle through the list of events For Each objEvent in colEvents ' Build up the description of the logged event strDescription = "Date: " & mid(objEvent.TimeWritten,7,2) & "/" &_ mid(objEvent.TimeWritten,5,2) & "/" &_ mid(objEvent.TimeWritten,1,4) & vbTab &_ "Source: " & objEvent.SourceName & vbNewline &_ "Time: " & mid(objEvent.TimeWritten,9,2) & ":" & _ mid(objEvent.TimeWritten,11,2) & ":" &_ mid(objEvent.TimeWritten,13,2) & vbTab &_ "Category: " & objEvent.Category & vbNewline &_ "Type: " & objEvent.Type & vbTab &_ "EventID: " & objEvent.EventCode & vbNewline &_ "User: " & objEvent.User & vbNewline &_ "Computer: " & objEvent.ComputerName & vbNewline &_ "Description: " & vbNewline &_ objEvent.Message taEventLogDescription.InnerText = strDescription Next 'objEvent ' Free any memory used by variables Set colEvents = Nothing End Sub
Microsoft Access Guide to Success: From Fundamentals to Mastery in Crafting Databases, Optimizing Tasks, & Making Unparalleled Impressions [III EDITION]