Jan 26

Running VBScripts with UAC Elevation

Overview

Since the introduction of User Account Control (UAC), scripts do not run with administrator privileges despite being a local administrator.  You must elevate your script to run with administrator privileges. I’ll start by showing you a simple example.  The script below will list all of the processes on the local computer as well as the WIN32_Process CommandLine property.  If you run the script on a computer with UAC without elevating it, you will only see CommandLine values for processes created by your account; if any other processes were created by another account, the CommandLine property will be NULL.

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process",,48)
For Each objItem in colItems
Wscript.Echo "Process: " & objItem.Name & vbCrLf & _
"Startup: " & objItem.CommandLine
Next

 

On a test machine, I was logged on as User1, opened notepad, and launched a vbscript as the local administrator account using RunAs.  I ran the script above and compared the results to task manager with the following results:

As you can see, the script successfully showed the CommandLine property for the currently logged on user

User1 Test Script Notepad Process Results

User1 Task Manager Notepad Process Results

However, the test script failed to show the CommandLine property for the wscript.exe process running as administrator:

Administrator Test Script Wscript Process Results

Administrator Task Manager Wscript Process Results

By re-running the test script with elevated privileges, the script now successfully shows the CommandLine property for the wscript process running as Administrator.

Administrator Elevated Test Script Wscript Process Results

Now that I have successfully demonstrated the need to run a script elevated on a local machine, you might be wondering what happens when you the test script on a remote machine.  If you run the script on a remote machine that you have administrator rights on, it will successfully display the CommandLine property for all users.  Now, you might be confused as to why it works remotely?  The answer is quite simple, the script is elevated by RPC.  Now that you have a good understanding of running vbscripts with UAC elevation, here are some methods on how to elevate them.

 

 Method 1 – Elevating Using the Command Prompt

  1. Click Start, All Programs, Click Accessories
  2. Right-click Command Prompt and click Run as administratorRun Elevated Command Prompt
  3. Click Yes
    1. CMD UAC Prompt
  4. Any script you launch using wscript.exe or cscript.exe will launch elevated

Method 2 – RunAs Script

This method uses a wrapper script to run an elevated VBScript using the runas verb with the ShellExecute method of Shell.Application.  When it launches the elevated script, click Yes

http://sigkillit.com/2013/01/25/elevatewscript-vbs/

VBS UAC Prompt

 

Method 3 – Add ‘Run as administrator’ to the .vbs File Context Menu

The ‘Run as administrator’ option on a File Context Menu is only available on certain file types by default, and .vbs files are not one of them.  However, by doing a quick registry modification we can enable the ‘Run as administrator’ option o the file context menu.  Download and run the following registry to merge it into your registry, or you can copy the below text and save it to a .reg file:

Add Run as administrator to VBS File Context Menu

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\VBSFile\Shell\runas]
"HasLUAShield"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\VBSFile\Shell\runas\Command]
@=hex(2):22,00,25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,74,\
00,25,00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,57,00,\
53,00,63,00,72,00,69,00,70,00,74,00,2e,00,65,00,78,00,65,00,22,00,20,00,22,\
00,25,00,31,00,22,00,20,00,25,00,2a,00,00,00

 

Jan 25

ElevateWscript.vbs

'=========================================================================
' ElevateWscript.vbs
' VERSION: 1.0
' AUTHOR: Brian Steinmeyer
' EMAIL: sigkill@sigkillit.com
' WEB: http://sigkillit.com
' DATE: 1/25/2012
' COMPATIBLE: Windows Vista, Server 2008, and Above
' COMMENTS: Since the introduction of UAC in Windows, despite being an
' administrator you may still need to run a script with elevated
' privileges. For example the CommandLine property of the WIN32_Process class
' requires a script to be elevated in order to return valid data when the process
' is running as another user. Unfortunately, Windows does not provide Run As
' Administrator on the context of a .vbs file, which is why I made this.
' To use the script, pass the full path to a .vbs file to the Sub and it
' will prompt you to run the script elevated. If the script you need to elevate
' in located in the same directory as this script, you can just pass the script
' name. Alternatively, you can always launch your vbscript from an elevated
' command prompt which will use wscript or cscript elevated as well.
' EXAMPLE: Elevate a script using the full path
'          Call ElevateWscript("C:\scripts\test.vbs")
' EXAMPLE: Elevate a script in the same directory as ElevateWscript.vbs
'          Call ElevateWscript("test.vbs")
'=========================================================================
Option Explicit
Call ElevateWscript("test.vbs")

Private Sub ElevateWscript(scriptName)
    Dim objShell: Set objShell = CreateObject("Shell.Application")
    Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
    If objFSO.FileExists(scriptName) Then
        Dim objFile: Set objFile = objFSO.GetFile(scriptName)
         objShell.ShellExecute "wscript.exe", Chr(34) & objFile.Path & Chr(34), "", "runas", 1
    Else
         Wscript.Echo "Script Does Not Exist!" & vbCrLf & scriptName
    End If
End Sub

 

Jan 24

Find Email Address in Active Directory

Did you ever try to create a new email address and receive an error message that it already exists?  Or did you ever have someone ask who is using an email address?  Here are some methods to find the email address:

1 – Active Directory Users and Computers Saved Queries (Server 2003 and up)

  • In Active Directory Users and Computers, right-click the Saved Queries container and click New->Query
  • Enter a name for the query then click the Define Query button
  • Click the Find drop-down menu and click Custom Search
  • Click the Advanced tab and enter the following query (Replace jdoe@domain.com with the email you want to find)
(proxyAddresses=SMTP:jdoe@domain.com)
  • Click OK

LDAP proxyAddresses Query

 

2 – Exchange 2010/2007 Management Shell

To find a particular email address use the following command (Replace jdoe@domain.com with the email you want to find)

get-recipient | where {$_.emailaddresses -match “jdoe@domain.com”} | select name,emailaddresses

To find all email addresses for a particular domain use the following command (Replace domain.com with the domain you want to find)

get-recipient | where {$_.emailaddresses -match “domain.com”} | select name,emailaddresses

 

 

3 – Outlook

In Outlook, create a new message and type the email address into the to field.  Click the Check Names button or press Ctrl+K to resolve the email to the display name.  Note: this will not work if recipient is hidden from the GAL or Address List!!!

Jan 23

Identify a Windows VM Disk in vSphere

If you have ever worked with VMWare’s vSphere, I’m sure there has come a time that you needed to modify or remove Windows VM Disk.  Sure, it’s a simple enough task, but what if you have multiple disks that are the same size?  How can you correctly identify the virtual disk in vSphere?  Luckily, it is quite easy to identify a virtual disk in a Windows VM.

Identify the Bus and Target ID in the Windows VM

On your Windows VM, open Server Manager.  In Server Manager, Expand Storage and click on Disk Management.  Right Click on a Disk and click Properties (Note: Make sure you right click on the left side where it says Disk #, don’t right-click on the right side where it has the partition).

Disk Properties

On the General Tab, locate the Bus # and Target Id and record the values for each disk.

VM Bus and Target ID

Identify the Windows Disk in vSphere

In vSphere, open the properties of your virtual machine.  If you select a virtual disk, the SCSI or IDE Controller and ID is displayed under Virtual Device Node.  Using this information, you can match it to the Windows Disk.  The SCSI/IDE Controller # will match the Bus # and the SCSI/IDE ID will match the Target Id.  Ex: Bus 0, Target Id 1 in Windows matches SCSI(0:1) in vSphere.

Virtual Device Node

Jan 22

ComputerInventory.vbs

'=========================================================================
' ComputerInventory.vbs
' VERSION: 1.0
' AUTHOR: Brian Steinmeyer
' EMAIL: sigkill@sigkillit.com
' WEB: http://sigkillit.com
' DATE: 1/21/2013
' COMPATIBLE: Windows XP+, Server 2003+. If you are using on Windows 2003,
'  to get correct CPU Physical and Core Counts make sure you have the following
'  hotfix installed: http://support.microsoft.com/kb/932370
' COMMENTS: Loops through a line delineated list of servers and reports back
'  the Manufacturer, Model #, Serial #, Windows OS, OS Architecture (32vs64),
'  RAM(MB), CPU Description, CPU Speed(GHz), CPU Physical Count, CPU Core Count,
'  Local Volumes with Total and Used Space in GB.
'  Edit the configuration to point to a text file containing the names of
'  the computers to inventory. By default, it will search the same directory
'  of the script, otherwise you can provide the full path. Also, set the max
'  number of Disk Volumes you want to return. By default, this is set to 5 but,
'  you may need to increase this number if your computers use a lot of volumes.
' EXAMPLE: Inventory Servers.txt in the Current Directory with a max of 5 volumes
'  Dim computerList: computerList = "servers.txt"
'  Dim maxVolumes: maxVolumes = 5
' EXAMPLE: Inventory Servers.txt using a full path with a max of 8 volumes
'  Dim computerList: computerList = "C:\servers.txt"
'  Dim maxVolumes: maxVolumes = 8
'=========================================================================
Option Explicit
' ------ SCRIPT CONFIGURATION ------
Dim computerList: computerList = "servers.txt"
Dim maxVolumes: maxVolumes = 5
' ------ END CONFIGURATION ------

'Ensure Computer List Exists
Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(computerList) Then
    Wscript.Echo "ERROR - Input File Does Not Exist!" & vbCrLf & vbCrLf & "Quitting Script!"
    Wscript.Quit
End If

'Create Log File
Dim strLogFile: strLogFile = Replace(Wscript.ScriptName, ".vbs", ".txt")
Dim strHeadings: strHeadings = "COMPUTER" & vbTab & _
    "MAKE" & vbTab & _
    "MODEL" & vbTab & _
    "SERIAL" & vbTab & _
    "OS" & vbTab & _
    "ARCHITECTURE" & vbTab & _
    "RAM(MB)" & vbTab & _
    "CPU" & vbTab & _
    "SPEED(GHz)" & vbTab & _
    "PHYSICAL" & vbTab & _
    "CORE"
Dim i
Dim strVolumes: strVolumes = ""
If maxVolumes > 0 Then
    For i = 1 to maxVolumes
        strVolumes = strVolumes & vbTab & "HDD(Used/Total)"
    Next
Else
    'Default to Single Volume If an Invalid # Was Assigned
    maxVolumes = 1
End If
strHeadings = strHeadings & strVolumes
Call Logger(strLogFile, strHeadings, True)

'Get Server Info
Const ForReading = 1
Dim objTextFile: Set objTextFile = objFSO.OpenTextFile(computerList, ForReading)
Dim strComp, strManufacturer, strModel, strSerial, strOS, strOSArchitecture, strRAM, strProcessor, strVolume, strTemp
Do Until objTextFile.AtEndOfStream
    strComp = Trim(objTextFile.Readline)
    If strComp <> "" Then
        If ServerUpTime(strComp) = "!~ERROR~!" Then
            strTemp = strComp & "(Offline)" & vbTab & _
                "!~ERROR~!" & vbTab & _
                "!~ERROR~!" & vbTab & _
                "!~ERROR~!" & vbTab & _
                "!~ERROR~!" & vbTab & _
                "!~ERROR~!" & vbTab & _
                "!~ERROR~!" & vbTab & _
                "!~ERROR~!" & vbTab & _
                "!~ERROR~!" & vbTab & _
                "!~ERROR~!" & vbTab & _
                "!~ERROR~!" & Replace(strVolumes, "HDD(Used/Total)", "!~ERROR~!")
            Call Logger(strLogFile, strTemp, False)
        Else   
            strManufacturer = GetManufacturer(strComp)
            strModel = GetModel(strComp)
            strSerial = GetSerial(strComp)
            strOS = GetOS(strComp)
            strOSArchitecture = GetOSArchitecture(strComp)
            strRAM = GetRAM(strComp)
            strProcessor = GetProcessor(strComp)
            strVolume = GetVolume(strComp, maxVolumes)
            Call Logger(strLogFile, strComp & vbTab & strManufacturer & vbTab & strModel & vbTab & strSerial & vbTab & strOS & vbTab & strOSArchitecture & vbTab & strRAM & vbTab & strProcessor & vbTab & strVolume, False)
        End If
    End If
Loop           
Wscript.Echo "Finished"

Private Function ServerUpTime(strComputer)

    On Error Resume Next

    Dim objWMISettings: Set objWMISettings = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Dim colItems: Set colItems = objWMISettings.ExecQuery("Select * from Win32_OperatingSystem")
    Dim strResult
    Dim objItem, dtmBootup, dtmLastBootupTime, dtmSystemUptime
    For Each objItem in colItems
        dtmBootup = objItem.LastBootUpTime
        dtmLastBootupTime = CDate(Mid(dtmBootup, 5, 2) & "/" & Mid(dtmBootup, 7, 2) & "/" & Left(dtmBootup, 4) & " " & Mid (dtmBootup, 9, 2) & ":" & Mid(dtmBootup, 11, 2) & ":" & Mid(dtmBootup, 13, 2))
        dtmSystemUptime = DateDiff("h", dtmLastBootUpTime, Now)
    Next

    'Return Results
    If Err.Number <> 0 Then
        Err.Clear
        strResult = "!~ERROR~!"
    Else
        strResult = dtmSystemUptime
    End If 
    ServerUpTime = strResult

    'Kill Objects
    Set objWMISettings = Nothing

    On Error GoTo 0  ' End Error Handling

End Function

Private Function GetManufacturer(strComputer)

    On Error Resume Next

    Dim objWMIService: Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Dim colItems: Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
    Dim strResult
    Dim objItem
    For Each objItem in colItems
        strResult = Trim(objItem.Manufacturer)
    Next

    'Return Results
    If Err.Number <> 0 Then
        Err.Clear
        strResult = "!~ERROR~!"
    End If
    GetManufacturer = strResult

    'Kill Objects
    Set objWMIService = Nothing

    On Error Goto 0

End Function

Private Function GetModel(strComputer)

    On Error Resume Next

    Dim objWMIService: Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Dim colItems: Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
    Dim strResult
    Dim objItem
    For Each objItem in colItems
        strResult = Trim(objItem.Model)
    Next

    'Return Results
    If Err.Number <> 0 Then
        Err.Clear
        strResult = "!~ERROR~!"
    End If
    GetModel = strResult

    'Kill Objects
    Set objWMIService = Nothing

    On Error Goto 0

End Function

Private Function GetSerial(strComputer)

    On Error Resume Next

    Dim objWMIService: Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Dim colItems: Set colItems = objWMIService.ExecQuery("Select * from Win32_BIOS")
    Dim strResult
    Dim objItem
    For Each objItem in colItems
        strResult = Trim(objItem.SerialNumber)
    Next

    'Return Results
    If Err.Number <> 0 Then
        Err.Clear
        strResult = "!~ERROR~!"
    End If
    GetSerial = strResult

    'Kill Objects
    Set objWMIService = Nothing

    On Error Goto 0

End Function

Private Function GetOS(strComputer)

    On Error Resume Next

    Dim objWMIService: Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Dim colItems: Set colItems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
    Dim strResult
    Dim objItem
    For Each objItem in colItems
        strResult = Trim(objItem.Caption)
    Next

    'Return Results
    If Err.Number <> 0 Then
        Err.Clear
        strResult = "!~ERROR~!"
    End If
    GetOS = strResult

    'Kill Objects
    Set objWMIService = Nothing

    On Error Goto 0

End Function

Private Function GetOSArchitecture(strComputer)

    On Error Resume Next

    Dim objWMIService: Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,authenticationLevel=Pkt}!\\" & strComputer & "\root\cimv2")
    Dim colItems: Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Processor")
    Dim strResult
    Dim objItem
    For Each objItem In colItems
        Select Case objItem.Architecture
            Case 0
                strResult = "32-bit"
            Case 9
                strResult = "64-bit"           
        End Select
    Next

    'Return Results
    If Err.Number <> 0 Then
        Err.Clear
        strResult = "!~ERROR~!"
    End If 
    GetOSArchitecture = strResult

    'Kill Ovjects
    Set objWMIService = Nothing

    On Error Goto 0

End Function

Private Function GetRAM(strComputer)

    On Error Resume Next

    Dim objWMIService: Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Dim colItems: Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
    Dim strResult
    Dim objItem
    For Each objItem in colItems
        strResult = Round(objItem.TotalPhysicalMemory/1024/1024,0)
    Next

    'Return Results
    If Err.Number <> 0 Then
        Err.Clear
        strResult = "!~ERROR~!"
    End If 
    GetRAM = strResult

    'Kill Objects
    Set objWMIService = Nothing

    On Error Goto 0

End Function

Private Function GetProcessor(strComputer)

    'If Using Server 2003 Install the Following Hotfix to Get Correct Physical and Core CPU Counts
    'http://support.microsoft.com/kb/932370

    On Error Resume Next

    Dim objWMIService: Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
    Dim colItems: Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Processor")
    Dim strResult
    Dim objItem
    Dim strCPU: strCPU = ""
    Dim strSpeed: strSpeed = ""
    Dim intPhysical: intPhysical = 0
    Dim intCores: intCores = 0
    For Each objItem in colItems
        strCPU = objItem.Description
        strSpeed = Round(objItem.CurrentClockSpeed/1000,2)
        intPhysical = colItems.Count
        intCores = objItem.NumberOfCores
    Next

    'Return Results
    If Err.Number <> 0 Then
        Err.clear
        strResult = "!~ERROR~!" & vbTab & "!~ERROR~!" & vbTab & "!~ERROR~!" & vbTab & "!~ERROR~!"
    Else
        strResult = strCPU & vbTab & strSpeed & vbTab & intPhysical & vbTab & intCores
    End If     
    GetProcessor = strResult

    'Kill Objects
    Set objWMIService = Nothing

    On Error Goto 0

End Function

Private Function GetVolume(strComputer, maxVolCount)

    On Error Resume Next

    Dim objWMIService: Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Dim colItems: Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk WHERE DriveType='3'")
    Dim strResult: strResult = ""
    Dim objItem, totalSpace, usedSpace
    Dim i: i = 0
    For Each objItem in colItems
        totalSpace = FormatNumber(objItem.Size/1024/1024/1024)
        usedSpace = FormatNumber((objItem.Size - objItem.FreeSpace)/1024/1024/1024)
        i = i + 1
        If i = 1 Then
            strResult = objItem.DeviceID & "(" & usedSpace & "/" & totalSpace & ")"
        Elseif i > maxVolCount Then
            'Skip
        Else
            strResult = strResult & vbTab & objItem.DeviceID & "(" & usedSpace & "/" & totalSpace & ")"
        End If
    Next
    If colItems.Count < maxVolCount Then
        For i = 1 to maxVolCount - colItems.Count
            strResult = strResult & vbTab & "N/A"
        Next
    End If

    'Return Results
    If Err.Number <> 0 Then
        Err.Clear
        If maxVolCount > 0 Then
            For i = 1 to maxVolCount
                If i = 1 Then
                    strResult = "!~ERROR~!"
                Else
                    strResult = strResult & vbTab & "!~ERROR~!"
                End If
            Next
        Else
            strResult = "!~ERROR~!"
        End If
    End If 
    GetVolume = strResult

    'Kill Objects
    Set objWMIService = Nothing

    On Error Goto 0

End Function

Private Sub Logger(fileName, logMessage, blnNewLog)

    On Error Resume Next

    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
    Dim scriptPath: scriptPath = Left(WScript.ScriptFullName,InstrRev(WScript.ScriptFullName,"\"))
    Dim logName
    If InStr(1,fileName,"\",1) > 0 Then
        logName = fileName
        If objFSO.DriveExists(objFSO.GetDriveName(logName)) Then
            If StrComp(objFSO.GetExtensionName(logName), "", 1) = 0 Then
                If Not objFSO.FolderExists(logName) Then
                    If objFSO.FolderExists(objFSO.GetParentFolderName(logName)) Then
                        objFSO.CreateFolder logName 'Create Folder In Current Path
                        Exit Sub
                    Else
                        Call Logger(objFSO.GetParentFolderName(logName), logMessage, blnNewLog) 'Recurse Creating Parent Folder
                        Call Logger(logName, logMessage, blnNewLog) 'Recurse Creating Current Folder
                        Exit Sub
                    End If
                End If
            Else
                If Not objFSO.FileExists(logName) Then
                    If Not objFSO.FolderExists(objFSO.GetParentFolderName(logName)) Then
                        Call Logger(objFSO.GetParentFolderName(logName), logMessage, blnNewLog)  'Recurse Creating Parent Folder
                        Call Logger(logName, logMessage, blnNewLog)  'Recurse Creating Current Folder
                    End If
                End If
            End If
        End If
    Else
        logName = scriptPath & fileName
    End If
    Dim logFile
    If blnNewLog = True Then
        Set logFile = objFSO.CreateTextFile(logName, True)
    Else
        If objFSO.FileExists(logName) Then
            Set logFile = objFSO.OpenTextFile(logName, ForAppending, True)
        Else
            Set logFile = objFSO.CreateTextFile(logName, True)
        End If
    End If
    logFile.WriteLine logMessage
    logFile.Close
    Set objFSO = Nothing

    On Error Goto 0

End Sub

 

Jan 18

PingHost.vbs

'=========================================================================
' PingHost.vbs
' VERSION: 1.0
' AUTHOR: Brian Steinmeyer
' EMAIL: sigkill@sigkillit.com
' WEB: http://sigkillit.com
' DATE: 1/17/2013
' COMMENTS: Pass a hostname or IP to the function and the number of times
' you wish to ping the host/IP, and it will return whether it is succesful
' or not.
' EXAMPLE: Ping by Hostname
' Dim strHost: strHost = "Server"
' Dim intCount: intCount = 4
' EXAMPLE: Ping by IP
' Dim strHost: strHost = "192.168.1.1"
' Dim intCount: intCount = 4
'=========================================================================
Option Explicit
' ------ SCRIPT CONFIGURATION ------
Dim strHost: strHost = "Server"
Dim intCount: intCount = 4
' ------ END CONFIGURATION ------

Wscript.Echo PingHost(strHost, intCount)

Private Function PingHost(strHostOrIP, count)

	On Error Resume Next ' Start Error Handling

	'Set Variables
	Dim objPing, objRetStatus, i, strResult: strResult = ""

	For i = 1 to count
		Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("select * from Win32_PingStatus where address = '" & strHostOrIP & "'")
		For Each objRetStatus in objPing
			If IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode<>0 Then
				strResult = "!~ERROR~!" & objRetStatus.StatusCode
				'WScript.Echo "Status code is " & objRetStatus.StatusCode
			Else
				strResult = "OK"
				'Wscript.Echo "Bytes = " & vbTab & objRetStatus.BufferSize
				'Wscript.Echo "Time (ms) = " & vbTab & objRetStatus.ResponseTime
				'Wscript.Echo "TTL (s) = " & vbTab & objRetStatus.ResponseTimeToLive
			End If
		Next

		' Error Check
		If Err.Number <> 0 Then
		strResult = "!~ERROR~!"
		End If

		'Check For Success
		If strResult = "OK" Then
			Exit For
		End If
		count = count -1
	Next

	'Return Result
	PingHost = strResult

	On Error GoTo 0 ' End Error Handling

End Function

 

Jan 18

CheckHTTPStatus.vbs

'=========================================================================
' CheckHTTPStatus.vbs
' VERSION: 1.0
' AUTHOR: Brian Steinmeyer
' EMAIL: sigkill@sigkillit.com
' WEB: http://sigkillit.com
' DATE: 1/17/2013
' COMMENTS: Pass the URL and optionally a username/password to the Function
' and it will check the HTTP return status code.
' EXAMPLE: Check If Website is Running
'          Dim strURL: strURL = "http://www.domain.com"
'          Dim strUsername: strUsername = ""
'          Dim strPassword: strPassword = ""
'=========================================================================
Option Explicit
' ------ SCRIPT CONFIGURATION ------
Dim strURL: strURL = "http://www.domain.com"
Dim strUsername: strUsername = ""
Dim strPassword: strPassword = ""
' ------ END CONFIGURATION ------

Wscript.Echo CheckHTTPStatus(strURL, strUsername, strPassword)

Function CheckHTTPStatus(url, uname, password)

    On Error Resume Next  ' Start Error Handling

    Dim strResult
    ' Create Objects
    'Dim objHTTP: Set objHTTP = createobject("msxml2.xmlhttp")
    Dim objHTTP: Set objHTTP = WScript.CreateObject("MSXML2.ServerXMLHTTP.6.0")
    objHTTP.SetOption 2, 13056  ' Ignore all SSL errors

    ' Open Web Page
    objHTTP.open "GET", url, false, uname, password
    objHTTP.send

    ' Error Check and Get Results
    If Err.Number <> 0 Then
        strResult = "!~ERROR~!"
        If isnull(objHttp.Status) Then
            strResult = strResult & "UNKNOWN_STATUS"
        Else
            strResult = strResult & objHTTP.Status & " " & objHTTP.StatusText
        End If
    Else
        If isnull(objHTTP.status) Then
            strResult = "!~ERROR~!UNKNOWN_STATUS"
        Else
            If objHTTP.status < 200 or objHTTP.status >= 300 Then
                strResult = "!~ERROR~!"
            End If
            strResult = strResult & objHTTP.Status & " " & objHTTP.StatusText
        End If
    End If

    Set objHTTP = Nothing

    CheckHTTPStatus = strResult

    On Error Goto 0  ' End Error Handling

End Function

 

Jan 18

CheckServiceRunning.vbs

'=========================================================================
' CheckServiceRunning.vbs
' VERSION: 1.0
' AUTHOR: Brian Steinmeyer
' EMAIL: sigkill@sigkillit.com
' WEB: http://sigkillit.com
' DATE: 1/17/2013
' COMMENTS: Pass the computer/servername to the function and the Service name
' and it will return whether the service is running.
' EXAMPLE: Check if the Print Spooler is Running
'		   strComputer = "Server"
'          strService = "Spooler"
'=========================================================================
Option Explicit
' ------ SCRIPT CONFIGURATION ------
Dim strComputer: strComputer = "Server"
Dim strService: strService = "Spooler"
' ------ END CONFIGURATION ------

Wscript.Echo CheckServiceRunning(strComputer, strService)

Private Function CheckServiceRunning(strComputer, strService)

	On Error Resume Next  ' Start Services Info Error Handling

	' Set Variables
	Dim objService, strResult: strResult = "!~ERROR~!"

    Dim objWMIService: Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Dim colServiceList: Set colServiceList = objWMIService.ExecQuery("Select * from Win32_Service WHERE Name = '" & strService & "'")
    If colServiceList.Count = 1 Then
		For Each objService in colServiceList
			If objService.State = "Running" Then
				strResult = "Running"
			Else
				'Attempt to Start Sesrvice if Not Running
				strResult = StartService(strComputer, strService)
			End If
		Next
    End If

	' Error Check
	If Err.Number <> 0 Then
		'Wscript.Echo Err.Number & vbCrLf & Err.Source & vbCrLf & Err.Description
		Err.Clear
		strResult = "!~ERROR~!"
	End If

	' Return Result
	CheckServiceRunning = "(" & strService & ")" & strResult

	On Error GoTo 0  ' End Services  Info Error Handling

End Function

 

Jan 14

DHCP Message Class

Here is a class I wrote to generate a DHCP message.  It’s primary purpose is to send a DHCP message, which can be useful for finding DHCP servers on a network

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Globalization;
using System.Text.RegularExpressions;

namespace SigkillDHCP
{
public class DhcpMessage
{
private const UInt32 MagicNumber = 1666417251;
//http://search.cpan.org/~shadinger/Net-DHCP-0.66/lib/Net/DHCP/Packet.pm

//Declare Fields
private DhcpOp _op;
private DhcpHtype _htype;
private byte _hlen;
private byte _hops;
private int _xid;
private UInt16 _secs;
private UInt16 _flags = 128;
private string _ciaddr = "0.0.0.0";
private string _yiaddr = "0.0.0.0";
private string _siaddr = "0.0.0.0";
private string _giaddr = "0.0.0.0";
private string _chaddr;
private byte[] _sname = new byte[64];
private byte[] _file = new byte[128];
//OPTIONS
private byte[] _mcookie = new byte[4];
private Dictionary<dhcpoption, byte[]=""> _options = new Dictionary<dhcpoption, byte[]="">();

#region Constructors

public DhcpMessage()
{
//Default Constructor Zero Fields
}

public DhcpMessage(byte[] data)
{
//Initiate DHCP Instance Fields When Reading Packet From DHCP Server
int Offset = 0;
byte[] tempip = new byte[4];
//MessageBox.Show("Op:" + BitConverter.ToString(data, Offset, 1).Replace("-", ""));
this._op = (DhcpOp)data[Offset];
Offset++;

this._htype = (DhcpHtype)data[Offset];
Offset++;

this._hlen = data[Offset];
Offset++;

this._hops = data[Offset];
Offset++;

this._xid = BitConverter.ToInt32(data, Offset);
Offset += 4;

this._secs = BitConverter.ToUInt16(data, Offset); //Need to reverse Byte order???
Offset += 2;

this._flags = BitConverter.ToUInt16(data, Offset);
Offset += 2;

Array.Copy(data, Offset, tempip, 0, 4);
this._ciaddr = new IPAddress(tempip).ToString();
Offset += 4;

Array.Copy(data, Offset, tempip, 0, 4);
this._yiaddr = new IPAddress(tempip).ToString();
Offset += 4;

Array.Copy(data, Offset, tempip, 0, 4);
this._siaddr = new IPAddress(tempip).ToString();
Offset += 4;

Array.Copy(data, Offset, tempip, 0, 4);
this._giaddr = new IPAddress(tempip).ToString();
Offset += 4;

this._chaddr = BitConverter.ToString(data, Offset, 6);
Offset += 16;

Array.Copy(data, Offset, this._sname, 0, 64);
Offset += 64;

Array.Copy(data, Offset, this._file, 0, 128);
Offset += 128;

//Check for DHCP Magic Cookie
if (BitConverter.ToUInt32(data, Offset) == MagicNumber)
{
Offset += 4;
Boolean end = false;

//Loop Other DHCP Options
while (!end && Offset < data.Length)
{
DhcpOption Option = (DhcpOption)data[Offset];
Offset++;

int OptionLength;
switch (Option)
{
case DhcpOption.Pad:
continue;
case DhcpOption.End:
end = true;
continue;
default:
OptionLength = (int)data[Offset];
Offset++;
break;
}

byte[] OptionData = new byte[OptionLength];
Array.Copy(data, Offset, OptionData, 0, OptionLength);
Offset += OptionLength;
this._options.Add(Option, OptionData);
}

}
}
#endregion

#region Properties
public DhcpOp Op
{
get { return this._op; }
set { this._op = value; }
}

public DhcpHtype Htype
{
get { return this._htype; }
set { this._htype = value; }
}

public byte Hlen
{
get { return this._hlen; }
set { this._hlen = value; }
}

public byte Hops
{
get { return this._hops; }
set { this._hops = value; }
}

public int Xid
{
get { return this._xid; }
set { this._xid = value; }
}

public UInt16 Secs
{
get { return this._secs; }
set { this._secs = value; }
}

public UInt16 Flags
{
get { return this._flags; }
set { this._flags = value; }
}

public string Ciaddr
{
get { return this._ciaddr; }
set
{
if (ValidateIp(value) == false)
{
throw new Exception("Invalid IP Specified for Ciaddr");
}
this._ciaddr = value;
}
}

public string Yiaddr
{
get { return this._yiaddr; }
set
{
if (ValidateIp(value) == false)
{
throw new Exception("Invalid IP Specified for Yiaddr");
}
this._yiaddr = value;
}
}

public string Siaddr
{
get { return this._siaddr; }
set
{
if (ValidateIp(value) == false)
{
throw new Exception("Invalid IP Specified for Siaddr");
}
this._siaddr = value;
}
}

public string Giaddr
{
get { return this._giaddr; }
set
{
if (ValidateIp(value) == false)
{
throw new Exception("Invalid IP Specified for Giaddr");
}
this._giaddr = value;
}
}

public string Chaddr
{
get { return this._chaddr; }
set
{
if (ValidateMac(value) == false)
{
throw new Exception("Invalid MAC Specified for Chaddr");
}
this._chaddr = value.Replace(":", "").Replace("-", "").Replace(".", "");
}
}

public byte[] Sname
{
get { return this._sname; }
set { this._sname = value; }
}

public byte[] File
{
get { return this._file; }
set { this._file = value; }
}

#endregion

#region IP-Binary Conversions
public string IpToBitString(string Address)
{
//Convert IP String to Octets
byte[] IP = IPAddress.Parse(Address).GetAddressBytes();
string IPBits = "";

//Loop Octets and Convert to Binary
for (int i = 0; i < IP.Length; i++)
{
IPBits += PadBinary(Convert.ToString(IP[i], 2), 8);
}
return IPBits;
}

public string PadBinary(string Bits, int TotalBits)
{
//Pad Bit Strings to Ensure Proper Length
//ex: Decimal 4 converts to 100 as a Binary String
// But We Want to Pad it to 8 bits as 00000100
string PadBits = "";
if (Bits.Length < TotalBits)
{
for (int i = 0; i < (TotalBits - Bits.Length); i++)
{
PadBits += "0";
}
Bits = PadBits + Bits;
}
return Bits;
}

public string BitStringToIp(string Bits)
{
//Convert 32bit Binary to IP String
string IP = "";
if (Bits.Length == 32)
{
IP = BinaryStringToInt(Bits.Substring(0, 8)).ToString() + ".";
IP += BinaryStringToInt(Bits.Substring(8, 8)).ToString() + ".";
IP += BinaryStringToInt(Bits.Substring(16, 8)).ToString() + ".";
IP += BinaryStringToInt(Bits.Substring(24, 8)).ToString();
}
else
{
IP = "127.0.0.1";
}
return IP;
}

public int BinaryStringToInt(string Bits)
{
//Converts a Binary String to Integer Based on Most Significant Bit
//ex: Binary 00000100 and Binary 100 Converts to Integer 4
int Number = 0;
for (int i = 0, Exp = (Bits.Length - 1); i < Bits.Length; i++, Exp--)
{
if (Bits[i].ToString() == "1")
{
Number += (int)Math.Pow(2, Exp);
}
}
return Number;
}
#endregion

#region Subnet Calculations
public int GetNetworkPrefix(string Mask)
{
//Convert Subnet Mask to Bit String
Mask = IpToBitString(Mask);

//Get Network Prefix
int Prefix = 0;
for (int i = 0; i < Mask.Length; i++)
{
if (Mask[i].ToString() == "1")
{
Prefix++;
}
}
return Prefix;
}

public string GetSubnetNumber(string Address, string Mask)
{
//Convert IP and SubnetMask String to Octets
byte[] IP = IPAddress.Parse(Address).GetAddressBytes();
byte[] SM = IPAddress.Parse(Mask).GetAddressBytes();
string SubnetNumber = "";

//Loop Octets Then Bitwise Boolean AND the IP and Subnet Mask
for (int i = 0; i < IP.Length; i++)
{
if (i < (IP.Length - 1))
{
SubnetNumber += (IP[i] & SM[i]).ToString() + ".";
}
else
{
SubnetNumber += (IP[i] & SM[i]).ToString();
}
}
return SubnetNumber;
}

public string GetSubnetBroadcast(string Mask, string SubnetNumber)
{
//Get Prefix
int Prefix = GetNetworkPrefix(Mask);

//Copy Network/Subnet Bits of SubnetNumber Then Replace Host Bits with 1's
string SNBits = IpToBitString(SubnetNumber);
string Broadcast = "";
for (int i = 0; i < SNBits.Length; i++)
{
if (i < Prefix)
{
Broadcast += SNBits[i];
}
else
{
Broadcast += "1";
}
}

//Convert Broadcast From Binary to IP
Broadcast = BitStringToIp(Broadcast);

return Broadcast;
}

public string GetSubnetFirstAddress(string SubnetNumber)
{
//Convert Subnet Number String to Octets
byte[] IP = IPAddress.Parse(SubnetNumber).GetAddressBytes();
string FirstAddress = "";

//First Address Equals Subnet Number Plus 1 in the Last Octet
IP[IP.Length - 1] += 1;

//Loop Octets to Build IP
for (int i = 0; i < IP.Length; i++)
{
if (i < (IP.Length - 1))
{
FirstAddress += IP[i].ToString() + ".";
}
else
{
FirstAddress += IP[i].ToString();
}
}
return FirstAddress;
}

public string GetSubnetLastAddress(string Broadcast)
{
//Convert Broadcast String to Octets
byte[] IP = IPAddress.Parse(Broadcast).GetAddressBytes();
string LastAddress = "";

//Last Address Equals Broadcast Minus 1 in the Last Octet
IP[IP.Length - 1] -= 1;

//Loop Octets to Build IP
for (int i = 0; i < IP.Length; i++)
{
if (i < (IP.Length - 1))
{
LastAddress += IP[i].ToString() + ".";
}
else
{
LastAddress += IP[i].ToString();
}
}
return LastAddress;
}

public int GetNetworkBits(string Address)
{
//Convert IP String to Octets
byte[] IP = IPAddress.Parse(Address).GetAddressBytes();

//Determine Network Bits Based on IP Class
if ((IP[0] >= 1) && (IP[0] <= 126))
{
//Class A 8 Network Bits
return 8;
}
else if ((IP[0] >= 128) && (IP[0] <= 191))
{
//Class B 16 Network Bits
return 16;
}
else if ((IP[0] >= 192) && (IP[0] <= 223))
{
//Class C 24 Network Bits
return 24;
}
else
{
//Error Invalid
return 0;
}
}

public int GetHostBits(string Mask)
{
//Convert Subnet Mask to Binary
string SM = IpToBitString(Mask);
int HostBits = 0;

for (int i = 0; i < SM.Length; i++)
{
if (SM[i].ToString() == "0")
{
HostBits++;
}
}
return HostBits;
}

public int GetSubnetBits(int NetworkBits, int HostBits)
{

return (32 - (NetworkBits + HostBits));
}

public int GetMaxSubnets(int SubnetBits, bool ClassfulProtocol)
{
//Determine Number of Subnets
if (ClassfulProtocol == true)
{
//Use ((2^s)-2) When:
//Classful routing protocol, Rip Ver 1 or IGRP protocol used, or no ip subnet zero command is configured
//Subtract 2 because Subnet Zero and Broadcast Subnet are reserved
return ((int)Math.Pow(2, SubnetBits) - 2);
}
else
{
//Use 2^s When:
//Classless routing protocol, Rip Ver 2 EIGRP or OSPF protocol used, ip subnet zero is configured or omitted, VLSM used, no other clues
//Subnet Zero and Broadcast Subnet are not reserved and can be used
return (int)Math.Pow(2, SubnetBits);
}
}

public int GetMaxHosts(int HostBits)
{
//Use ((2^h) - 2) Subtract 2 for the Subnet Number and Broadcast Address
return ((int)Math.Pow(2, HostBits) - 2);
}
#endregion

#region Methods

public bool ValidateIp(string testip)
{
IPAddress ip;
bool valid = false;
if (string.IsNullOrEmpty(testip))
{
valid = false;
}
else
{
valid = IPAddress.TryParse(testip, out ip);
}
return valid;
}

public bool ValidateMac(string testmac)
{
testmac = testmac.Replace(":", "").Replace("-", "").Replace(".", "");
bool valid = false;
if (testmac.Length == 12)
{
Regex rx = new Regex("([0-9a-fA-F][0-9a-fA-F]){6}");
if (rx.IsMatch(testmac))
{
valid = true;
}
}
return valid;
}

public byte[] MacToByte(string mac)
{
byte[] macBytes = BitConverter.GetBytes(long.Parse(mac, NumberStyles.HexNumber));
byte[] macAddress = new byte[6];
if (BitConverter.IsLittleEndian)
{
Array.Reverse(macBytes);
for (int i = 0; i <= 5; i++)
{
macAddress[i] = macBytes[i + 2];
}
}
return macAddress;
}

public byte[] GetOption(DhcpOption option)
{
if (this._options.ContainsKey(option))
{
return this._options[option];
}
else
{
return null;
}
}

public void AddOption(DhcpOption option, params byte[] val)
{
byte[] data = new byte[1 + val.Length];
data[0] = (byte)val.Length;
val.CopyTo(data, 1);
this._options.Add(option, data);
}

public int SessionId()
{
return (int)DateTime.Now.Ticks;
}

public byte[] StringToByteArray(string str, EncodingType encodingType)
{
System.Text.Encoding encoding = null;
switch (encodingType)
{
case EncodingType.ASCII:
encoding = new System.Text.ASCIIEncoding();
break;
case EncodingType.Unicode:
encoding = new System.Text.UnicodeEncoding();
break;
case EncodingType.UTF7:
encoding = new System.Text.UTF7Encoding();
break;
case EncodingType.UTF8:
encoding = new System.Text.UTF8Encoding();
break;
}
return encoding.GetBytes(str);
}

public static string ByteArrayToString(byte[] bytes, EncodingType encodingType)
{
System.Text.Encoding encoding = null;
switch (encodingType)
{
case EncodingType.ASCII:
encoding = new System.Text.ASCIIEncoding();
break;
case EncodingType.Unicode:
encoding = new System.Text.UnicodeEncoding();
break;
case EncodingType.UTF7:
encoding = new System.Text.UTF7Encoding();
break;
case EncodingType.UTF8:
encoding = new System.Text.UTF8Encoding();
break;
}
return encoding.GetString(bytes);
}

public byte[] ClassToByteArray()
{
//Minimum DHCP Message Size + Magic Cookie + End
int DhcpMsgSize = 236 + 4 + 1;
foreach (KeyValuePair<dhcpoption, byte[]=""> pair in this._options)
{
DhcpMsgSize += 1 + pair.Value.Length;
}

byte[] data = new byte[DhcpMsgSize];
int Offset = 0;

data[Offset] = (byte)this._op;
Offset++;

data[Offset] = (byte)this._htype;
Offset++;

data[Offset] = this._hlen;
Offset++;

data[Offset] = this._hops;
Offset++;

BitConverter.GetBytes(this._xid).CopyTo(data, Offset);
Offset += 4;

BitConverter.GetBytes(this._secs).CopyTo(data, Offset); //Need to reverse Byte order???
Offset += 2;

BitConverter.GetBytes(this._flags).CopyTo(data, Offset);
Offset += 2;

IPAddress.Parse(this._ciaddr).GetAddressBytes().CopyTo(data, Offset);
Offset += 4;

IPAddress.Parse(this._yiaddr).GetAddressBytes().CopyTo(data, Offset);
Offset += 4;

IPAddress.Parse(this._siaddr).GetAddressBytes().CopyTo(data, Offset);
Offset += 4;

IPAddress.Parse(this._giaddr).GetAddressBytes().CopyTo(data, Offset);
Offset += 4;

MacToByte(this._chaddr).CopyTo(data, Offset);
Offset += 16;

this._sname.CopyTo(data, Offset);
Offset += 64;

this._file.CopyTo(data, Offset);
Offset += 128;

BitConverter.GetBytes(MagicNumber).CopyTo(data, Offset);
Offset += 4;

if (this._options.Count > 0)
{
foreach (DhcpOption option in this._options.Keys)
{
//Copy Option
data[Offset] = (byte)option;
Offset++;

//Copy Option Data
Array.Copy(this._options[option], 0, data, Offset, this._options[option].Length);
Offset += this._options[option].Length;
}
}
data[Offset] = (byte)DhcpOption.End;
return data;
}
#endregion

}
#region Packet Examples
//byte[] discoverMessage = {
// /* Opt */0x01,
// /* Htype */0x01,
// /* Hlen */0x06,
// /* Hops */0x00,
// /* XID */0x00, 0x00, 0x00, 0x01,
// /* Sec */0x00, 0x00,
// /* Flags */0x80, 0x00,
// /* Ciaddr */0x00, 0x00, 0x00, 0x00,
// /* Yiaddr */0x00, 0x00, 0x00, 0x00,
// /* Siaddr */0x00, 0x00, 0x00, 0x00,
// /* Giaddr */0x00, 0x00, 0x00, 0x00,
// /* Chaddr */0x00, 0x11, 0x22, 0x33, 0x44, 0x55,
// /* Sname */0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// /* File */0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// /* DHCP OPTIONS */
// /* Mcookie */0x63, 0x82, 0x53, 0x63,
// /* ClientID */0x3d, 0x06, 0x00, 0x1f, 0x3b, 0x5b, 0xbd, 0xad,
// /* Hostname */0x0c, 0x05, 0x52, 0x6f, 0x67, 0x75, 0x65,
// /* DHCPDiscover */0x35, 0x01, 0x01,
// /* ParamReqList */0x37, 0x01, 0x03,
// /* EndOption */0xff
// };
#endregion

#region Enumerations
public enum DhcpOp : byte
{
//Number Operation Code - RFC1700
BootRequest = 0x01,
BootReply
}

public enum DhcpHtype : byte
{
//Number Hardware Type - RFC1700
Ethernet = 0x01,
ExperimentalEthernet,
AmateurRadio,
ProteonTokenRing,
Chaos,
Ieee802Networks,
Arcnet,
Hyperchannel,
Lanstar
}

public enum DhcpMsgType : byte
{
//DHCP Message Type - RFC2132, RFC4388
Discover = 0x01,
Offer,
Request,
Decline,
Ack,
Nak,
Release,
Inform,
ForceRenew,
LeaseQuery,
LeaseUnassigned,
LeaseUnknown,
LeaseActive
}

public enum DhcpOption : byte
{
//DHCP Options - RFC2132
Pad = 0x00,
SubnetMask = 0x01,
TimeOffset = 0x02,
Router = 0x03,
TimeServer = 0x04,
NameServer = 0x05,
DomainNameServer = 0x06,
Hostname = 0x0C,
DomainNameSuffix = 0x0F,
AddressRequest = 0x32,
AddressTime = 0x33,
DhcpMessageType = 0x35,
DhcpAddress = 0x36,
ParameterList = 0x37,
DhcpMessage = 0x38,
DhcpMaxMessageSize = 0x39,
ClassId = 0x3C,
ClientId = 0x3D,
AutoConfig = 0x74,
End = 0xFF
}

public enum EncodingType
{
ASCII,
Unicode,
UTF7,
UTF8
}

#endregion

}

 

Jan 04

GroupModifyManager.vbs

'=========================================================================
' GroupModifyManager.vbs
' VERSION: 1.0
' AUTHOR: Brian Steinmeyer
' EMAIL: sigkill@sigkillit.com
' WEB: http://sigkillit.com
' DATE: 1/4/2013
' COMMENTS: This will set the manager for a group and optionally allow them
' to update group membership. Set the manager by specificying the LDAP path
' or DN of the user you want to set. Set the group to modify by specifying
' the LDAP path or DN of a specific group; you can also set this to an OU
' to make bulk changes. Last, specify whether the manager can update the
' group membership by setting the True/False value.
' EXAMPLE: Modify a Specific Group's Manager and Allow Them to Update Membership
'          Dim strManager: strManager = "LDAP://CN=John Doe,OU=User,DC=domain,DC=com"
'          Dim strGroupPath: strGroupPath = "LDAP://CN=Testgroup,OU=Groups,DC=domain,DC=com"
'          Dim blnUpdateMembership: blnUpdateMembership = True
' EXAMPLE: Modify a Specific Group's Manager and Do Not Allow Them to Update Membership
'          Dim strManager: strManager = "LDAP://CN=John Doe,OU=User,DC=domain,DC=com"
'          Dim strGroupPath: strGroupPath = "LDAP://CN=Testgroup,OU=Groups,DC=domain,DC=com"
'          Dim blnUpdateMembership: blnUpdateMembership = False
' EXAMPLE: Bulk Modify All Group's Managers in an OU and Allow Them to Update Membership
'          Dim strManager: strManager = "LDAP://CN=John Doe,OU=User,DC=domain,DC=com"
'          Dim strGroupPath: strGroupPath = "LDAP://OU=Groups,DC=domain,DC=com"
'          Dim blnUpdateMembership: blnUpdateMembership = True
'=========================================================================
Option Explicit
' ------ START CONFIGURATION ------
Dim strManager: strManager = "LDAP://CN=John Doe,OU=User,DC=domain,DC=com"
Dim strGroupPath: strGroupPath = "LDAP://OU=Groups,DC=domain,DC=com"
Dim blnUpdateMembership: blnUpdateMembership = True
' ------ END CONFIGURATION ------

Dim strLogName: strLogName = Replace(WScript.ScriptName,".vbs",".txt")
Call Logger(strLogName, "", True)
Call ModifyManger(strGroupPath, strManager, blnUpdateMembership, strLogName)
Wscript.Echo "Finished"

Private Sub ModifyManger(groupPath, groupManager, groupUpdateMembership, groupLogName)

    On Error Resume Next

    'Ensure DN not ADS Path
    groupPath = Replace(groupPath,"LDAP://","",1,1,1)
    groupManager = Replace(groupManager,"LDAP://","",1,1,1)

    'Constants/Variables to Set Manager Update List Access
    Const ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = &H5
    Const ADS_RIGHT_DS_WRITE_PROP = &H20
    Const ADS_ACEFLAG_INHERIT_ACE = &H00002 'Not Needed but Kept it here for Reference
    Const ADS_ACEFLAG_DONT_INHERIT_ACE = &H0
    Const ADS_FLAG_OBJECT_TYPE_PRESENT = &H01
    Const ADS_OBJECT_WRITE_MEMBERS = "{BF9679C0-0DE6-11D0-A285-00AA003049E2}"
    Dim objSecurityDescriptor, objDACL, objUser, objACE

    'Connect to AD
    Dim objConnection: Set objConnection = CreateObject("ADODB.Connection")
    Dim objCommand: Set objCommand = CreateObject("ADODB.Command")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open "Active Directory Provider"
    Set objCommand.ActiveConnection = objConnection
    objCommand.Properties("Page Size") = 1000   'Override the Return 1000 Results Default
    Const ADS_SCOPE_SUBTREE = 2
    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE    'Include Sub OU's
    objCommand.CommandText = "SELECT ADsPath FROM 'LDAP://" & strGroupPath & "' WHERE objectClass='group'"
    Dim objRecordSet: Set objRecordSet = objCommand.Execute
    If Not objRecordSet.RecordCount > 0 Then
        Call Logger(groupLogName, "Error No Groups Found Quitting Script!", False)
        Exit Sub
    End If
    objRecordSet.MoveFirst
    Dim objGroup
    Do Until objRecordSet.EOF
        Call Logger(groupLogName, objRecordSet.Fields("ADsPath").Value & vbCrLf & "**********************************************", False)
        Set objGroup = GetObject(objRecordSet.Fields("ADsPath").Value)
        objGroup.Put "managedBy", groupManager
        objGroup.SetInfo
        If Err.Number <> 0 Then
            Err.Clear
            Call Logger(groupLogName, "Error Updating Manager to: " & groupManager, False)
        Else
            Call Logger(groupLogName, "Success Updating Manager to: " & groupManager, False)
            If groupUpdateMembership = True Then
                'Allow Manager to Update Member List
                Call Logger(groupLogName, "Allow Manager to Update Member List: True", False)
                Set objSecurityDescriptor = objGroup.Get("ntSecurityDescriptor")
                Set objDACL = objSecurityDescriptor.DiscretionaryACL
                Set objUser = GetObject("LDAP://" & objGroup.Get("managedBy"))
                Set objACE = CreateObject("AccessControlEntry")
                objACE.Trustee = "snapretail\" & objUser.Get("sAMAccountName")
                objACE.AccessMask = ADS_RIGHT_DS_WRITE_PROP
                objACE.AceFlags = ADS_ACEFLAG_DONT_INHERIT_ACE
                objACE.AceType = ADS_ACETYPE_ACCESS_ALLOWED_OBJECT
                objACE.Flags = ADS_FLAG_OBJECT_TYPE_PRESENT
                objACE.objectType = ADS_OBJECT_WRITE_MEMBERS
                objDACL.AddAce(objACE)
                objSecurityDescriptor.DiscretionaryACL = objDACL
                objGroup.Put "ntSecurityDescriptor", Array(objSecurityDescriptor)
                objGroup.SetInfo
                If Err.Number <> 0 Then
                    Err.Clear
                    Call Logger(groupLogName, "Error Allowing Manager to Update Member List", False)
                Else
                    Call Logger(groupLogName, "Success Allowing Manager to Update Member List", False)
                End If
            End If
        End If

        Call Logger(groupLogName, "" & vbCrLf, False)

        objRecordSet.MoveNext

    Loop

    On Error Goto 0

End Sub

Private Sub Logger(fileName, logMessage, blnNewLog)

    On Error Resume Next

    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
    Dim scriptPath: scriptPath = Left(WScript.ScriptFullName,InstrRev(WScript.ScriptFullName,"\"))
    Dim logName
    If InStr(1,fileName,"\",1) > 0 Then
        logName = fileName
        If objFSO.DriveExists(objFSO.GetDriveName(logName)) Then
            If StrComp(objFSO.GetExtensionName(logName), "", 1) = 0 Then
                If Not objFSO.FolderExists(logName) Then
                    If objFSO.FolderExists(objFSO.GetParentFolderName(logName)) Then
                        objFSO.CreateFolder logName 'Create Folder In Current Path
                       Exit Sub
                    Else
                        Call Logger(objFSO.GetParentFolderName(logName), logMessage, blnNewLog) 'Recurse Creating Parent Folder
                       Call Logger(logName, logMessage, blnNewLog) 'Recurse Creating Current Folder
                       Exit Sub
                    End If
                End If
            Else
                If Not objFSO.FileExists(logName) Then
                    If Not objFSO.FolderExists(objFSO.GetParentFolderName(logName)) Then
                        Call Logger(objFSO.GetParentFolderName(logName), logMessage, blnNewLog)  'Recurse Creating Parent Folder
                       Call Logger(logName, logMessage, blnNewLog)  'Recurse Creating Current Folder
                   End If
                End If
            End If
        End If
    Else
        logName = scriptPath & fileName
    End If
    Dim logFile
    If blnNewLog = True Then
        Set logFile = objFSO.CreateTextFile(logName, True)
    Else
        If objFSO.FileExists(logName) Then
            Set logFile = objFSO.OpenTextFile(logName, ForAppending, True)
        Else
            Set logFile = objFSO.CreateTextFile(logName, True)
        End If
    End If
    logFile.WriteLine logMessage
    logFile.Close
    Set objFSO = Nothing

    On Error Goto 0

End Sub