Categories
VBScript

VBScript : Find User SID

VBScript : Find User SID

Teh following script can be modified to return the SID of a user object. Change to be the hostname of a local DC, to be the sAMAccountNameof the user who’s SID you wish to find, and finally to be the NETBIOS name of the Active Directory domain:

strComputer = “
Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)

Set objAccount = objWMIService.Get _
    (“Win32_UserAccount.Name=’‘,Domain=’‘”)
Wscript.Echo objAccount.SID

For example this could be changed to:

strComputer = “DC1
Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)

Set objAccount = objWMIService.Get _
    (“Win32_UserAccount.Name=’BloggsJ‘,Domain=’MYDOMAIN‘”)
Wscript.Echo objAccount.SID

Categories
VBScript

vbScript : Disable Windows Search Install

Outlook 2007 : Disable Windows Search Install Prompt

The Windows Desktop Search functionality can slow down Microsoft Outlook 2007, as well as a users entire workstation. The following machine startup script will disable prompts for users to install this plug-in normally gernerated by Microsoft Outlook.

‘Script to Disable Windows Search For Outlook 2007
Const ForReading = 1
Const ForWriting = 2
Const HKEY_CURRENT_USER  = &H80000001

Set WshShell = CreateObject(“WScript.Shell”)
Set fso = CreateObject(“Scripting.FileSystemObject”)
windir = WshShell.ExpandEnvironmentStrings(“%windir%”)

Set objNetwork = CreateObject(“Wscript.Network”)
currentDomain = objNetwork.UserDomain
currentUser = objNetwork.UserName

‘Disable Windows Desktop Search Prompts
InstallDIR = WshShell.ExpandEnvironmentStrings(“%PROGRAMFILES%”) & “\Microsoft Office\Office12”
target = InstallDIR & “\OUTLOOK.exe”
If fso.FileExists(target) Then    ‘If there is no Outlook 2007 executable install Outlook 2007    
    Set objNetwork = CreateObject(“Wscript.Network”)
    Set wmiLocator = CreateObject(“WbemScripting.SWbemLocator”) ‘ Object used to get StdRegProv Namespace
    Set wmiNameSpace = wmiLocator.ConnectServer(objNetwork.ComputerName, “root\default”) ‘ Registry Provider (StdRegProv) lives in root\default namespace.
    Set objRegistry = wmiNameSpace.Get(“StdRegProv”)
    objRegistry.SetDWORDValue HKEY_CURRENT_USER,”Software\Microsoft\Office\12.0\Outlook\Search”,”DisableDownloadSearchPrompt”,1
End If

Categories
VBScript

VBScript : Find Windows Hardware Architecture

VBScript : Find Windows Hardware Architecture

The following VBscript will establish whether the local system is x86 or x64 and enable you to execute further commands based upon this. Simply copy the code into a new .vbs file and add the additional steps within the if statement.

Set WshShell = WScript.CreateObject("WScript.Shell")
vArchitecture = WshShell.RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE")

If vArchitecture = "AMD64" Then
   '64 bit OS
    wscript.echo "64-bit OS"
ElseIf vArchitecture = "x86" Then
  '32 bit OS
   wscript.echo "32-bit OS"
End If

 

Categories
VBScript

VBScript : Find Files By Owner

The following code will list all files which a particular user owns, you will need to ‘pipe’ its output to a file using the following command: cscript.exe find-own.vbs > files.txt

Set objShell = CreateObject (“Shell.Application”)
Set objStartFolder = objShell.Namespace (“N:\”)
Set objFSO = CreateObject(“Scripting.FileSystemObject”)

strUsername = “NETBIOSNAME\sAMAccountName”
oFolder = “N:\”

Dim arrHeaders(13)

ShowSubfolders objFSO.GetFolder(oFolder)

Sub ShowSubFolders(Folder)
On Error Resume Next
    For Each Subfolder in Folder.SubFolders
        Set oNsp = objShell.Namespace(Subfolder.Path)
        ‘Dim arrHeaders(13)
        For i = 0 to 13
            arrHeaders(i) = oNsp.GetDetailsOf (oNsp.Items, i)
        Next

        For Each strFileName in oNsp.Items
            If LCASE(oNsp.GetDetailsOf (strFileName, 8)) = LCASE(strUsername) Then
       
            Wscript.Echo Subfolder.Path & “\” & strFilename & “,” & arrHeaders(1) & “,” & Replace(oNsp.GetDetailsOf (strFileName, 1),”,”,””)
            End If
        Next
    ShowSubFolders Subfolder
    Next
End Sub

Categories
VBScript

VBScript ; Ping Test

The following code will ping a semi-colon de-limited list of computers, displaying output on the command windows. Save the file as ping.vbs and call using the following command: cscript.exe ping.vbs

Set WshShell = CreateObject(“WScript.Shell”)

strPCs = “host1;host2”
strPCs = Split(strPCs,”;”)

For each PC in strPCs
    PingTest(PC)
Next

Sub PingTest(strComputer)
    Set objScriptExec = WshShell.Exec(“ping ” & strComputer)
    Do While Not objscriptexec.Stdout.AtEndOfStream
        str = objscriptexec.Stdout.ReadLine   
        If InStr(1,str,”Lost = 0″,1) > 0 Then
            WScript.Echo(”   ” & strComputer & “: OK – 100%”)
        ElseIf    InStr(1,str,”Lost = 1″,1) > 0 Then
            WScript.Echo(”   ” & strComputer & “: FAIL – 75%”)
        ElseIf    InStr(1,str,”Lost = 2″,1) > 0 Then
            WScript.Echo(”   ” & strComputer & “: FAIL – 50%”)
        ElseIf    InStr(1,str,”Lost = 3″,1) > 0 Then
            WScript.Echo(”   ” & strComputer & “: FAIL – 25%”)
        ElseIf InStr(1,str,”Lost = 4″,1) > 0 Then
            WScript.Echo(”   ” & strComputer & “: FAIL – 0%”)
        End If
    Loop
End Sub

Categories
VBScript

VBScript ; Set UserPreferencesMask Binary Registry Key

Set UserPreferencesMask Binary Registry Key

 

An ideal solution for configuring display options for ‘best performance’ on Citrix and Terminal Servers:

 

 

Simply add the following code to an existing VB logon script or create a new one to run along side you exusting scrip:

Const HKEY_CLASSES_ROOT  = &H80000000
Const HKEY_CURRENT_USER  = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
Const HKEY_USERS         = &H80000003

Set WshShell = CreateObject(“WScript.Shell”)

‘Lookup User Account Name and Logon Domain Name
Set objNetwork = CreateObject(“Wscript.Network”)
currentDomain = objNetwork.UserDomain
currentUser = objNetwork.UserName

Set wmiLocator = CreateObject(“WbemScripting.SWbemLocator”) ‘ Object used to get StdRegProv Namespace
Set wmiNameSpace = wmiLocator.ConnectServer(objNetwork.ComputerName, “root\default”) ‘ Registry Provider (StdRegProv) lives in root\default namespace.
Set objRegistry = wmiNameSpace.Get(“StdRegProv”)

uBinary = Array(&H90,&H12,&H01,&H80)
cmd = objRegistry.SetBinaryValue(HKEY_CURRENT_USER, “Control Panel\Desktop”, “UserPreferencesMask”, uBinary) 

The changes will be applied at second logon (ie first logon the change is written to the users hive, at second logon this setting will be used) 

Categories
VBScript

VBScript ; Find User Group Memberships (+ Nested groups)

VBScript ; Find User Group Memberships (including Nested groups)

 

This fast, simple logon script will enumerate a user accounts group memberships, including nested groups.

 

‘Obtain fqdn of domain
Set oRoot = GetObject(“LDAP://rootDSE”)
Set oDomain = GetObject(“LDAP://” & oRoot.Get(“defaultNamingContext”))
fqDomain = oRoot.Get(“defaultNamingContext”)

‘Obtain netbios username, computername and domainname
Set objNetwork = CreateObject(“Wscript.Network”)
currentDomain = objNetwork.UserDomain
currentUser = objNetwork.UserName
strComputerName = objNetwork.ComputerName


‘————————————————- Main Program

‘Find user DistingishedName and bind to user object to find nested group memberships
uCN = findDN
Set objUser=GetObject(“LDAP://” & uCN)

If IsMember(“Domain Admins”) Then
MsgBox “User is a member of the domain admins group….”
‘Perform required functions here.
End If


‘————————————————- Functions

Function IsMember(grpName) ‘Function to find groups to which user is a *DIRECT* member of.
If IsEmpty(grpList) Then
Set grpList = CreateObject(“Scripting.Dictionary”)
grpList.CompareMode = TextCompare

Set colGroups = objUser.Groups
For Each objGroup in colGroups
If NOT CBool(grpList.Exists(objGroup.CN)) Then
grpList.Add objGroup.CN, “-“
GetNested(objGroup)
End If
Next
End If
IsMember = CBool(grpList.Exists(grpName))
End Function

Function GetNested(objGroup) ‘New Recursive Nested Group Membership Function.
On Error Resume Next
colMembers = objGroup.GetEx(“memberOf”)
For Each strMember in colMembers
If NOT strMember = “” Then
strPath = “LDAP://” & strMember
Set objNestedGroup = GetObject(strPath)
If NOT CBool(grpList.Exists(objNestedGroup.CN)) Then
grpList.Add objNestedGroup.CN, “-“
GetNested(objNestedGroup)
End If
End If
Next
End Function

Function findDN ‘Funtion to find DistinguishedName of User Object using sAMAccountName
Set objConnection = CreateObject(“ADODB.Connection”)
objConnection.Open “Provider=ADsDSOObject;”

Set objCommand = CreateObject(“ADODB.Command”)
objCommand.ActiveConnection = objConnection

objCommand.CommandText = _
“<LDAP://” & fqDomain & “>;(&(objectCategory=” & “User” & “)” & _
“(samAccountName=” & currentUser & “));samAccountName,distinguishedName;subtree”

Set objRecordSet = objCommand.Execute

If objRecordset.RecordCount = 0 Then
WScript.Quit(0)
Else
findDN = objRecordSet.Fields(“distinguishedName”).Value
objConnection.Close
End If
End Function

Categories
VBScript

VBScript ; Check Operating System Service Pack Level

VBScript ; Check Op Save erating System Service Pack Level

The script below will output the current service pack of any Windows 2000+ Operating System. This is very useful if you are deploying software via logon script.

Const Impersonate = “winmgmts:{impersonationLevel=impersonate}!\\”
computer = “.”
Set oWMI = GetObject(Impersonate & computer & “\root\cimv2”)
Set QueryWMI = oWMI.ExecQuery(“SELECT * FROM Win32_OperatingSystem”)
For Each oItem In QueryWMI
spVer = oItem.ServicePackMajorVersion
Next

MsgBox “This computer has Service Pack ” & spVer & ” is installed.”

 

 

 

 

 

 

 

 

 

 

Categories
VBScript

VBScript ; Montior Exchange DB Size

VBScript ; Montior Exchange 2000/2003 Standard DB Size

Aimed at the SMB users running with the 16GB limit, this customisable vb script will warn you when the Microsoft Exchange Database size exceeds a certain size in GB.\r\n\r\nThe script could easily be modified for use with all versions of Exchange depending on what limit you’re worried about, be it software or hardware restricted.’, ‘Simply copy the following code into notepad and save it as a ‘.vbs’ file. The script needs to run from the mailserver itself, I run it as a scheduled task at start-up.

In order to avoid excessive notifications the script quits upon notification, you must re-run the script in order to continue monitoring.

You need to modify the areas highlighted in bold. I have configured the script to alert me via when the DB size reaches 15GB.

The script is called using a batch file which contains the following line:

cscript.exe c:\scripts\script_name.vbs

Dim fileSize, fileSize2, totalSize, checkFile, strComputer, objWMIService
Dim setFormat, MessageTitle, messageBody, SizeFormat

Set WshShell = CreateObject(“WScript.Shell”)
Set objNetwork = CreateObject(“Wscript.Network”)
Set fso = CreateObject(“Scripting.FileSystemObject”)

strComputer = “.”
Set objWMIService = GetObject(“winmgmts:” _
& “{impersonationLevel=impersonate}!\\” & _
strComputer & “\root\cimv2”)

Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
(“SELECT * FROM __InstanceModificationEvent WITHIN 10 WHERE ” _
& “TargetInstance ISA ‘CIM_DataFile’ and ” _
& “TargetInstance.Name=’e:\\ExchangeDB\\MDBDATA\\priv1.edb'”)

Do
Set objLatestEvent = colMonitoredEvents.NextEvent
filesize = 0
filesize2 = 0
totalSize = 0

target = “e:\ExchangeDB\MDBDATA\priv1.stm”
Set checkFile = fso.GetFile(target)

fileSize = SetBytes(checkFile.size)
filesize2 = SetBytes(objLatestEvent.TargetInstance.FileSize)

totalSize = filesize + filesize2
Wscript.Echo “Exchange DB size is” & totalSize & SizeFormat

If (filesize + filesize2 ) > 15 Then
messageBody = “Danger Will Robinson! Exchange DB size at ” & totalSize & SizeFormat & vbCrlf & vbCrlf _
& “Please restart this script on the server.”
SendEmail()
WScript.Quit()
End If
Loop

‘————————-
Function SetBytes(Bytes)
If Bytes >= 1073741824 Then
SetBytes = Round(FormatNumber(Bytes / 1024 / 1024 / 1024, 2), 2)
SizeFortmat = “GB”
ElseIf Bytes >= 1048576 Then
SetBytes = Round(FormatNumber(Bytes / 1024 / 1024, 2), 2)
SizeFortmat = “MB”
ElseIf Bytes >= 1024 Then
SetBytes = Round(FormatNumber(Bytes / 1024, 2), 2)
SizeFortmat = “KB”
ElseIf Bytes < 1024 Then
SetBytes = Bytes
SizeFortmat = “Bytes”
Else
SetBytes = “0 Bytes”
End If
End Function

‘————————————————
Sub SendEmail
Set objMessage = CreateObject(“CDO.Message”)

objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/sendusing”) = 2

‘FQDN / IP Of SMTP Server
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpserver”) = strComputer

‘SMTP Port
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpserverport”) = 25

objMessage.Configuration.Fields.Update

objMessage.Subject = strComputer & “: Exchange Database Size”
objMessage.From = “[email protected]
objMessage.To = “[email protected]
objMessage.TextBody = messageBody
objMessage.Send
End Sub

Categories
VBScript

VBScript ; Event ID 36 IWAM IIS Monitor

VBScript ; Event Log Monitor – Event ID36 W3SVCS and DCOM 10004 Errors

IIS IWAM accounts usually automatically sync every 7 days. This process was causing chaos on our AD domain with a variety of different IIS servers; from Citrix Web Interface servers to VMWare management pages.

Page Cannot Be Displayed Errors are accompanied by DCOM 10004 errors and W3SVC 36 errors in the System Event log. The problems can be resolved by running the ‘syniwam.vbs’ script. In order to both detect and eliminate this problem whilst we troubleshooted the root cause I wrote a script that would detect these errors in the event log and automatically run the synciwam.vbs script.

The vbscript file must be configured to run every 5 minutes on the server you wish to protect. The script will establish the local time difference from UTC (which is required when searching the event log). Once found it will check the System Event Log for any event code 36 errors in the last 5 minutes. If there are any the script will call the synciwam.vbs script file. The script will then send an email to the desired user via a mail server of choice. I have highlighted the code that you must change in bold.

You can change the search period and increase it from 5 minutes if required. I have made the text red on this part of the script. Remember if you do this to change the frequency of the scheduled task to match your required time period.

‘Event Log checker to protect IIS Web Sites

‘Contact Chris Bradford for details.

‘Option Explicit
Const ForReading = 1
Const ForWriting = 8
Const CONVERT_TO_LOCAL_TIME = True

Dim objFso, objFolder, objWMI, objEvent ‘ Objects
Dim strFile, strComputer, strFolder, strFileName, strPath ‘ Strings
Dim intEvent, intNumberID, intRecordNum, colLoggedEvents, arrHistory, Compare

For Each LocalTimeZone in GetObject(“winmgmts:”).InstancesOf(“Win32_ComputerSystem”)
TimeZoneOffset = LocalTimeZone.CurrentTimeZone
Next

Wscript.Echo “The current time difference is ” & TimeZoneOffset & ” minutes (” & TimeZoneOffset/60 & ” hrs)”

DateToCheck = CDATE(DateAdd(“n”,-5,Now))

If TimeZoneOffset > 0 Then
UTCDate = DateAdd(“n”, -ABS(TimeZoneOffset), DateToCheck)
Else
UTCDate = DateAdd(“n”, ABS(TimeZoneOffset), DateToCheck)
End if

WScript.Echo “UTC Date/Time: ” & UTCDate

Set objNetwork = CreateObject(“Wscript.Network”)
strComputerName = objNetwork.ComputerName

‘ ——————————————–
‘ Set your variables
intNumberID = 36 ‘ Event ID Number
intRecordNum = 0

strComputer = “.”

‘——————————————–
Set objWMI = GetObject(“winmgmts:” & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”)

WScript.Echo “Looking for events newer than: ” & UTCDate & “(UTC Date) and event ID: ” & intNumberID

Set colLoggedEvents = objWMI.ExecQuery(“Select * from Win32_NTLogEvent Where Logfile = ‘System’ AND TimeWritten > ‘” & UTCDate & “‘ and EventCode = ’36′”)
‘—————————————–

intEvent = 0
For Each objEvent in colLoggedEvents
IntEvent = intEvent +1
Next

WScript.Echo “Number of errors: ” & IntEvent

If intEvent > 0 Then
WScript.Echo “Error detected”
Set objShell = CreateObject(“WScript.Shell”)

command = “cscript.exe “
command_arg1 = “D:\Inetpub\AdminScripts\synciwam.vbs” ‘Location of synicwam AdminScript
objShell.Run command & command_arg1
SendEmail
End If

Sub SendEMail
Set objMessage = CreateObject(“CDO.Message”)

‘==This section provides the configuration information for the remote SMTP server.
‘==Normally you will only change the server name or IP.

objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/sendusing”) = 2

‘Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpserver”) = “mailserver”

‘Server port (typically 25)
objMessage.Configuration.Fields.Item _
(“http://schemas.microsoft.com/cdo/configuration/smtpserverport”) = 25

objMessage.Configuration.Fields.Update

‘==End remote SMTP server configuration section==

objMessage.Subject = strComputerName & “: W3SVC Error.”
objMessage.From = strComputerName & “@yourdomain.com”
objMessage.To = [email protected]
objMessage.TextBody = “W3SVC error detected on ” & ServerName & vbCr & vbCr & “synciwam.vbs automatically script run.”
objMessage.Send
End Sub