Showing posts with label Active Directory. Show all posts
Showing posts with label Active Directory. Show all posts

Friday, May 25, 2007

UpdSeniors2007.vbs: Student exit account shutdown

Author: Robert Lawson
Environment: Windows Server, Active Directory, Exchange, vb-script
Description: This script’s function is to do all Active Directory and Exchange steps for graduating students. The student accounts have been manually moved to a single Active Directory OU, from an approved list published by the Registrar. The Active Directory account and Exchange mailbox are logically removed from the system, eg removed from GAL, all group memberships removed, email address scrambled. This script can take several hours and can be run at off-hours.
Features:
- Results written to disk log file
- Trial no-update option
Code:
'=========================================================================
' FILE: UpdSeniors2007.vbs
' AUTHOR: Robert Lawson
' COMPANY: Soka University
' DATE: 25-May-2007
' COMMENT: Update/shutdown 2007 senior AD users
' Assumpitons
' 1. Run as Domain Admin
' 2. You have setup OU and moved seniors to this OU
' 4. Set to target Exchange mailbox
' 5. Must have installed "Exchange System Management Tools"on computer this script executes on. To
' do this you 1) Use Exchange CD, 2) Do Exchange installation
'=========================================================================
Option Explicit
' Variables
Dim fso, objFile, strRec, answer, logUpdate, objNetwork
Dim strOU, strFilter, strQuery, rs, objCommand, UserADsPath, objUser, objConnection
Dim strTargetHomeMDB_DN, strOriginalHomeMDB, objTargetHomeMDB, logSkipMoveMailBox
Dim proxyAddresses, proxyAddressesCount, i, email, emailOld, emailNew, objGroup, groupADsPath, objUserGroup
Dim dacl, ace, oSecurityDescriptor, sTrustee

' Constants
Const ADS_SCOPE_SUBTREE = 2
Const ADS_PROPERTY_DELETE = 4
Const ADS_PROPERTY_UPDATE = 2
Const ADS_PROPERTY_APPEND = 3
Const ADS_PROPERTY_CLEAR = 1

' Exchange AD Security
CONST ADS_ACETYPE_ACCESS_ALLOWED = 0
CONST ADS_ACEFLAG_INHERIT_ACE = 2

Const ForReading = 1
Const ForWriting = 2
Const consDisableAccount = 66050 ' AD user setting
Const consLogFile = "c:\temp\UpdSeniros2007.txt" ' File name to write data to
Const conScriptName = "UpdSeniors2007.vbs"
Const conADSelf = "NT AUTHORITY\SELF"

' ============================================================
' Log file setup
' ============================================================
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFile = fso.OpenTextFile(consLogFile, ForWriting, True)
Set objNetwork = Wscript.CreateObject("Wscript.Network")
strRec = "Date = " & Date & " " & Time & _
", Script= " & conScriptName & _
", Computer = " & objNetwork.ComputerName & _
", User = " & objNetwork.UserName & "/" & objNetwork.UserDomain
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr

' ============================================================
' Verify target mailbox exists
' ============================================================
strTargetHomeMDB_DN = "CN=ClassOf2007,CN=Students,CN=InformationStore,CN=server,CN=Servers,CN=First Administrative Group,CN=Administrative Groups,CN=uni,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=uni,DC=edu"
Set objTargetHomeMDB = CreateObject("CDOEXM.MailBoxStoreDB")
objTargetHomeMDB.DataSource.Open (strTargetHomeMDB_DN)
If Err.Number Then ErrorHandler (Err)
If objTargetHomeMDB.Status Then
strRec = "***ERROR: Target Store " & objTargetHomeMDB.Name & " is not mounted."
Wscript.Echo strRec
WScript.Quit (1)
else
strRec = "Target store verified: " & objTargetHomeMDB.Name
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr
End If

' ============================================================
' Get users
' ============================================================
set objConnection=Createobject("ADODB.Connection")
set objCommand=CreateObject("ADODB.Command")
objConnection.Provider="ADSDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

strOU = "OU=UG Graduates 2007,OU=Students,OU=Location,DC=uni,DC=edu"
strFilter = "objectcategory='person' AND objectclass='user'"

strQuery = "SELECT ADsPath from 'LDAP://" & strOU & "' WHERE " & strFilter
Wscript.Echo strQuery
objFile.WriteLine strQuery & vbCr

objCommand.CommandText= strQuery
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
' ============================================================
' Proceed?
' ============================================================
strRec = "OU = " & strOU & vbCrLF & _
"FILTER = " & strFilter & vbCrLF & _
"TARGETMB = " & strTargetHomeMDB_DN
answer=MsgBox(strRec,vbYesNoCancel + vbInformation + vbDefaultButton2,"Update?")
if answer = vbOK or answer = vbYes then
logUpdate = TRUE
else
logUpdate = FALSE
end if
strRec = "UPDATE = " & logUpdate
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr

' ============================================================
' Do Updates
' ============================================================
Set rs = objCommand.Execute
do while not rs.EOF
UserADsPath = rs.fields("ADsPath").value
Wscript.Echo UserADsPath
Set objUser = GetObject(UserADsPath)

strRec = "--Working on: " & objUser.sAMAccountname
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr

' ------------------------------------------------------------
' Move Exchange mailbox
strOriginalHomeMDB = objUser.homeMDB
logSkipMoveMailBox = ((LCase(strOriginalHomeMDB) = LCase(strTargetHomeMDB_DN)) or _
Isnull(strOriginalHomeMDB))
Wscript.Echo "logSkipMoveMailBox = " & logSkipMoveMailBox
if logUpdate and NOT logSkipMoveMailBox then
On Error Resume Next
objUser.MoveMailbox "LDAP://" & strTargetHomeMDB_DN
If err.Number Then
strRec = "***ERROR: Unable to move from homeMDB " & strOriginalHomeMDB
Wscript.Echo "strOriginalHomeMDB = " & strOriginalHomeMDB
Wscript.Echo "strTargetHomeMDB_DN = " & strTargetHomeMDB_DN
strRec = "err = " & err.number & " " & err.Description
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr
WScript.Quit (1)
else
strRec = "Moved mailbox from " & strOriginalHomeMDB & " to " & objUser.homeMDB
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr
End If
end if

' ------------------------------------------------------------
' Hide from Exchange GAL
if logUpdate and not objUser.msExchHideFromAddressLists then
strRec = "Setting msExchHideFromAddressLists = TRUE"
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr
objUser.Put "msExchHideFromAddressLists",TRUE
objUser.SetInfo
end if

' ------------------------------------------------------------
' Disable receiving email from outside
proxyAddresses = objUser.proxyAddresses
emailNew = ""
If Not IsNull(proxyAddresses) Then
proxyAddressesCount = UBound(proxyAddresses)
For i = 0 To proxyAddressesCount
email = proxyAddresses(i)
If Left(email,5) = "SMTP:" and instr(email,"XXX@") = 0 then
emailNew = email
emailOld = email
emailNew = replace(emailNew,"@","XXX@")
Wscript.Echo "Delete : " & email
Wscript.Echo "Adding: " & emailNew
proxyAddresses(i) = emailNew
end if
Next
if logUpdate and len(emailNew) > 0 then
strRec = "Changing " & emailOld & " to " & emailNew
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr
objUser.putex ADS_PROPERTY_UPDATE, "proxyAddresses",array(emailNew)
objUser.SetInfo
end if
End if

' ------------------------------------------------------------
' Remove group memberships
For Each objGroup In objUser.Groups
groupADsPath = objGroup.ADsPath
Wscript.Echo groupADsPath

if logUpdate then
Set objUserGroup = GetObject(groupADsPath)
strRec = "Removing membership to : " & objUserGroup.sAMAccountname
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr

objUserGroup.Remove(UserADsPath)
objUserGroup.Setinfo
end if
Next

' ------------------------------------------------------------
' Set MB rights (fixes problem in KB 555410)
Set oSecurityDescriptor = objUser.MailboxRights ' Get the Mailbox security descriptor (SD).
Set dacl = oSecurityDescriptor.DiscretionaryAcl 'Discretionary Access Control List (DACL)
Set Ace = CreateObject("AccessControlEntry")

if logUpdate then
strRec = "Fixing MB rights : " & objUser.sAMAccountname
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr

Ace.AccessMask = 131079 ' SELF
Ace.AceType = ADS_ACETYPE_ACCESS_ALLOWED
Ace.AceFlags = ADS_ACEFLAG_INHERIT_ACE
Ace.Flags = 0 '
Ace.Trustee = conADSelf
dacl.AddAce Ace

oSecurityDescriptor.DiscretionaryAcl = dacl
objUser.MailboxRights = oSecurityDescriptor
objUser.SetInfo
end if

' ------------------------------------------------------------
' Set account to inactive
if logUpdate and objUser.userAccountControl <> consDisableAccount then
strRec = "Setting userAccountControl = " & consDisableAccount & "(disabled)"
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr
objUser.Put "userAccountControl", consDisableAccount
objUser.SetInfo
end if

rs.movenext
Loop ' All users
' ============================================================
' The End
' ============================================================
strRec = "Date = " & Date & " " & Time & _
", Script= " & conScriptName & _
", Computer = " & objNetwork.ComputerName & _
", User = " & objNetwork.UserName & "/" & objNetwork.UserDomain
Wscript.Echo strRec
objFile.WriteLine strRec & vbCr

rs.Close
objFile.Close
objConnection.Close

Monday, December 25, 2006

dsq1.bat: common AD queries

Author: Robert Lawson
Environment: Windows Server, Active Directory
Description: These are the most common queries I use to gather information from Active Directory, and usually import results into Excel for auditing and/or reporting. I do save most common OU's to simply cut-and-paste, else I'll use ADSI-edit to get the OU. I simply remove the REM from query I want to use, then execute as such:

dsq1.bat>dsq1.txt
Uses:
- Stale passwords: report users who password is due to expire, call and educate before it expires. I did this for 1 year… no longer an issue
- Inactive computers: monitored for a year, removed manually. Then on negotiating with User Services, agreed to 9month and automatically remove.
- Mailbox store: audit that conventions were being followed: students, employees, non-named accounts, inactive…
- Group membership: quick way to get e-list of members
- Security: members of Domain Admin, Enterprise Admin..
- Ad hoc queries: total number of active students, employees….
Code:

rem file   : dsq1.bat
rem purpose: AD Query's
rem create : 25-dec-2006/r lawson
rem
rem notes
rem - un-REM query you want to use
rem - execute to verify no syntax error
rem - dsq1.cmd>dsq1.txt
rem - Import dsq1.txt into Excel for reporting

rem computers, in AV, inactive for 1 year
rem dsquery computer "DC=school,DC=edu" -inactive 52 -limit 0 dsget computer -samid -dn

rem all computer names
rem
rem dsquery computer "OU=AvServers,OU=location,DC=school,DC=edu" -limit 0 dsget computer -samid

rem computers, inactive for x weeks
rem dsquery computer "OU=Computer Accounts,DC=school,DC=edu" -limit 0 dsget computer -samid -sid -desc -loc
rem dsquery computer "OU=Computer Accounts,DC=school,DC=edu" -o rdn -limit 0 -inactive 12
rem dsquery * "OU=Computers,OU=Calabasas,DC=school,DC=edu" -attr cn operatingSystem operatingSystemServicePack lastlogonTimeStamp -limit 0


rem users, in Calabasas campus, with disabled accounts
rem dsquery user "OU=Calabasas,DC=school,DC=edu" -disabled -limit 0

rem all users, inactive for 1 year
rem dsquery user "DC=school,DC=edu" -inactive 26 -limit 0 dsget user -samid -display -disabled -dn

rem all users, who have not changed pw for 60 days
rem dsquery user "DC=school,DC=edu" -stalepwd 60 -limit 0
rem users who's password will expire in 5 days (90-85)
rem dsquery user "OU=Staff,OU=Users,OU=location,DC=school,DC=edu" -stalepwd 83 -limit 0 dsget user -samid -email -empid -display -title -dept -tel -office -disabled -canchpwd -pwdneverexpires -acctexpires -mustchpwd

rem all email enabled users
rem dsquery * "DC=school,DC=edu" -filter "(&(objectCategory=Person)(objectClass=User)(homeMDB=*)) " -attr sAMAccountName displayName distinguishedName homeMDB userAccountControl -limit 0


rem all Users in an OU
dsquery * "OU=Students,DC=school,DC=edu" -filter "(&(objectCategory=Person)(objectClass=User))" -attr sAMAccountName displayName givenName description sn employeeID employeeNumber department homeMDB userAccountControl -limit 0

rem another form of users in an OU
rem dsquery user "OU=janitors,OU=location,DC=school,DC=edu" -limit 0 dsget user -samid -display -disabled -canchpwd -pwdneverexpires -acctexpires

rem single user, display info
rem dsquery user "CN=edummy,OU=Consultants And Temporary Users,OU=All AV Employees,OU=location,DC=school,DC=edu" dsget user -samid -display -disabled -canchpwd -pwdneverexpires -acctexpires

rem get members of a group
rem dsquery group "OU=ADgroups,OU=location,DC=school,DC=edu" -name "grpUGClassOf2012"dsget group -members -expanddsget user -samid -fn -ln -title -dept -disabled -mustchpwd -pwdneverexpires

rem groups
rem dsquery * "OU=ADgroups,OU=location,DC=school,DC=edu" -filter "(&(objectCategory=Group)(objectClass=Group))" -limit 0 -attr sAMAccountName displayName name description mail member

rem users 1: AD attributes, LDAP filter
rem dsquery * "DC=school,DC=edu" -filter "(&(objectCategory=Person)(objectClass=User))" -limit 0 -attr sAMAccountName displayName employeeID employeeNumber userAccountControl delivContLength submissionContLength mdbUseDefaults mDBStorageQuota mDBOverHardQuotaLimit msExchHideFromAddressLists memberOf

rem Users 2: AD attributes
rem dsquery * "OU=Students,OU=location,DC=school,DC=edu" -limit 0 -attr sAMAccountName displayName employeeID employeeNumber telephoneNumber ciscoEcsbuDtmfId physicalDeliveryOfficeName createTimeStamp whenCreated department title userAccountControl msExchHideFromAddressLists mail protocolSettings homeMDB memberOf

rem Users 3: Query elements
rem dsquery user "OU=NewStudents,OU=Users,DC=school,DC=edu" -limit 0 dsget user -samid -email -empid -display -title -dept -tel -office -disabled -pwdneverexpires -acctexpires -mustchpwd


rem Users 3: Query elements, brief
rem dsquery user "OU=NewStudents,DC=school,DC=edu" -limit 0 dsget user -samid -fn -ln

rem computers with bogus container setting

rem dsquery * "OU=Computer Accounts,DC=school,DC=edu" -limit 0 -attr sAMAccountName CN msDS-Approx-Immed-Subordinates memberOf

rem find oddities with T/S (doesn't seem to work May 2006)
rem dsquery * "OU=Users,DC=school,DC=edu" -limit 0 -attr sAMAccountName displayName department title scriptPath TerminalServicesProfilePath TerminalServicesHomeDirectory TerminalServicesHomeDrive TerminalServicesWorkDirectory TerminalServicesInitialProgram

Saturday, December 2, 2006

UserOutlookRemovePSTref.vbs: Remove Outlook pst features

Author: Robert Lawson
Environment: Windows XP, Outlook, vb-script
Description: This script is run from Active Directory Group Policy log on script to disable Outlook personal mailbox files, pst files. The script includes a built-in method to deploy to pilot group. To make trouble shooting easier, all steps are written to application event log
Code:
'=========================================================================
' FILE : UserOutlookRemovePSTref.vbs
' AUTHOR : Robert Lawson
' COMPANY: Soka University of America
' DATE : 12/02/2006 Robert Lawson Creation Date
' COMMENT: Remove PST file references in Outlook profile
' Note, after this is run, the only repair to the Outlook profile is to delete it
' Office 2003 only (Office Versions: 11.0 = 2003; 10.0 = XP)
' Assume: 1) Outlook installed, 2) Outlook has been opened
' ' http://www.codecomments.com/message383229.html primary source of info
'=========================================================================
option explicit
On Error Resume Next ' Required
const conScriptName = "UserOutlookRemovePSTref.vbs"
const conDEBUG = FALSE
const conUpdateRegKeys = TRUE ' TRUE = will update Outlook reg keys
const conPilot = TRUE ' TRUE = script for pilot group of users, FALSE= all users considered

Dim strMsg, intLoc, objShell
Dim objNetwork, strUserName, strUserDomain, strGroupName, strComputerName
DIM Result, objReg, Return, strComputer, junk, count
Dim arrEntrynames(),Profile, arrProfiles(), ProfileSubkey, arrProfileSubKeys(), arrValueTypes(), arrValue
Dim strPSTFileName, strPSTRefence, strPSTKey, strRemoveKey, strKey
Const conOutlookProfileKey = "Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\"
Const HKCR=&H80000000 'HKEY_CLASSES_ROOT
Const HKCU=&H80000001 'HKEY_CURRENT_USER
Const HKLM=&H80000002 'HKEY_LOCAL_MACHINE
Const HKU=&H80000003 'HKEY_USERS
Const HKCC=&H80000005 'HKEY_CURRENT_CONFIG

' ============================================================
' Setup
' ============================================================
Set objShell = CreateObject( "WScript.Shell" )
Set objNetwork = Wscript.CreateObject("Wscript.Network")
strComputer = "."
Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
strMsg = "BEGIN: " & conScriptName
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
strComputerName = objNetwork.ComputerName
strUserName = objNetwork.UserName
strUserDomain = objNetwork.UserDomain
strMsg = conScriptName & " values: CN = " & strComputerName & "; UN = " & strUserName & "; DN = " & strUserDomain
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg

if (conPilot and NOT PilotByList(strUserName)) then
strMsg = conScriptName & "; Stopped. User not part of pilot group. User = " & strUserName
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
Wscript.Quit
end if ' Pilot

' ============================================================
' Main:
' ' Enumerate each Outlook profile for this user
' ' Remove key with PST file reference
' ============================================================
objReg.EnumKey HKCU, conOutlookProfileKey, arrProfiles
For Each Profile in arrProfiles
if conDEBUG then Wscript.Echo "Profile = " & Profile
objReg.EnumKey HKCU, conOutlookProfileKey & Profile & "\", arrProfileSubKeys
For Each ProfileSubkey In arrProfileSubKeys
strMsg = "ProfileSubkey = " & ProfileSubkey
if conDEBUG then Wscript.Echo strMsg
objReg.EnumValues HKCU,conOutlookProfileKey & Profile & "\" & ProfileSubKey & "\",arrEntryNames,arrValueTypes
Err.Clear
junk = UBound(arrEntryNames) ' Ignore keys that have no entries.
If Err.Number = 0 Then
strPSTFileName = ""
strPSTRefence = ""
strPSTKey = ProfileSubkey
For Count=0 To UBound(arrEntryNames)
' 001f6700 = Fully qualified file name
strKey = "001f6700"
If arrEntryNames(Count) = strKey Then
objReg.GetBinaryValue HKCU,conOutlookProfileKey & Profile & "\" & ProfileSubKey & "\",strKey,arrValue
strPSTFileName = BinaryToString(arrValue)
End If
' 001f3006 = Name of reference in Outlook
strKey = "001f3006"
If arrEntryNames(Count) = strKey Then
objReg.GetBinaryValue HKCU,conOutlookProfileKey & Profile & "\" & ProfileSubKey & "\",strKey,arrValue
strPSTRefence = BinaryToString(arrValue)
end if
Next ' UBound(arrEntryNames)
' Remove key(s) with PST file reference.
if LEN(strPSTFileName) > 0 then
strMsg = "*strPSTKey = " & strPSTKey & "; strPSTFileName = " & strPSTFileName & "; strPSTRefence =" & strPSTRefence
if conDEBUG then Wscript.Echo strMsg
strRemoveKey = conOutlookProfileKey & Profile & "\" & strPSTKey
strMsg = "*strRemoveKey = " & strRemoveKey
if conDEBUG then Wscript.Echo strMsg
if conUpdateRegKeys then
Return = objReg.DeleteKey(HKCU, strRemoveKey)
If (Return = 0) And (Err.Number = 0) Then
strMsg = conScriptName & ": REMOVED KEY: = " & strRemoveKey
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
strMsg = conScriptName & ": strPSTFileName = " & strPSTFileName & "; strPSTRefence =" & strPSTRefence
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
Else
Wscript.Echo conScriptName & ": DeleteKey failed. Error = " & Err.Number & " on key = " & strRemoveKey
objShell.LogEvent 0,strMsg
End If
end if
end if
End If
Next ' arrProfileSubKeys
Next ' arrProfiles
' ============================================================
' The End
' ============================================================
strMsg = "END: " & conScriptName
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
set objShell = nothing
Set objNetwork = Nothing
set objReg = nothing

' ============================================================
' Functions: BinaryToString
' ============================================================
Function BinaryToString(val)
Dim bByte, retval, i
For i = 0 To (UBound(val)-2) Step 2
bByte = val(i)
If bByte <> "" Then retval = retval & Chr(bByte)
Next
BinaryToString = retval
End Function

' ============================================================
' Function: PilotByList
' ============================================================
Function PilotByList(strUserID)
' PilotByList: determine pilot group by list of users
' strUserID String Passed User Network ID (sAMAccountname)
' PilotByList Boolean Returned TRUE=UserID is part of pilot group, FALSE=it aint
Dim strUser
PilotByList = FALSE ' default
strUser = lcase(strUserID) ' only lower case
PilotByList = ( _
strUser = "sleepy" or _
strUser = "sneezy" or _
strUser = "weepy" or _
strUser = "dopey" or _
strUser = "grumpy")
End Function ' PilotByList


Friday, October 27, 2006

DriveMapEmployee.vbs: Map network drive

Author: Robert Lawson
Environment: Windows Server, Active Directory, Group Policy, vb-script
Description: This script maps a user's network drive to a pre-reserved Windows drive for two campus. The campus is determined by user's primary IP address. This script is run at log on from Active Directory Group Policy. Each step is written to application event log for easy trouble shooting.

Code:

'=========================================================================
' FILE : DriveMapEmployee.vbs
' AUTHOR : Robert Lawson
' COMPANY: Soka University of America
' DATE : 10/27/2006
' COMMENT: Map primary drive for employees
'
'=========================================================================
Option Explicit
On Error Resume Next ' Required, or fails if already mapped

const conScriptName = "DriveMapEmployee.vbs"
const conDEBUG = TRUE

Dim objNetwork, objShell, objDrives
Dim strComputerName, strUserName, strUserDomain
Dim strDrive, strShare, strCurrentCampus, strDriveOld, strShareOld
Dim bolAlreadyMapped, bolAVCampus, bolCALCampus
Dim wmi, nics, nic, ip, strIP, i
Dim strMsg

Const conAVIP = "10."
Const conCALIP = "172.16"
Const conAVCampus = "AlisoViejo"
Const conCALCampus = "Calabasas"
Const conUNKCampus = "Unknown"
Const conAVshare = "\\server1\userstore\"
Const conCALshare = "\\rserver2\Employees\"
Const conMapDrive = "U:"

' ============================================================
' Setup
' ============================================================
Set objNetwork = Wscript.CreateObject("Wscript.Network")
Set objShell = CreateObject( "WScript.Shell" )

strMsg = "BEGIN: " & conScriptName
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg

' ============================================================
' Get user info
' ============================================================
strComputerName = objNetwork.ComputerName
strUserName = objNetwork.UserName
strUserDomain = objNetwork.UserDomain
strMsg = conScriptName & " values: CN = " & strComputerName & "; UN = " & strUserName & "; DN = " & strUserDomain
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg

' Get IP address (there could be multiple)
bolAVCampus = FALSE
bolCALCampus = FALSE
Set wmi = GetObject("winmgmts:\\.\root\cimv2")
Set nics = wmi.ExecQuery("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True")
For Each nic In nics
For Each ip In nic.ipaddress
strIP = ip
'strIP = "172.16.10.11" '*************** DEBUG
if conDEBUG then WScript.Echo "IP: " & strIP
if LEN(strIP) > 0 then
if left(strIP,3) = conAVIP then
bolAVCampus = TRUE
elseif left(strIP,6) = conCALIP then
bolCALCampus = TRUE
End if
End if
Next
Next

' You know current campus
if bolAVCampus then
strCurrentCampus = conAVCampus
elseif bolCALCampus then
strCurrentCampus = conCALCampus
else
strCurrentCampus = conUNKCampus
end if
if conDEBUG then Wscript.Echo "Campus = " & strCurrentCampus

' Did you figure out campus?
if strCurrentCampus = conUNKCampus then
strMsg = conScriptName & ": Unable to deterine campus from IP address"
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
WScript.Quit
end if

' ============================================================
' Map away
' ============================================================
strDrive = conMapDrive

if strCurrentCampus = conAVCampus then
strShare = conAVshare & strUserName
elseif strCurrentCampus = conCALCampus then
strShare = conCALshare & strUserName
end if

' Get current mapping
bolAlreadyMapped = False
Set objDrives = objNetwork.EnumNetworkDrives
For i = 0 to objDrives.Count - 1 Step 2
strDriveOld = objDrives.Item(i)
strShareOld = objDrives.Item(i+1)
if conDEBUG then WScript.Echo "Drive " & strDriveOld & " = " & strShareOld
bolAlreadyMapped = (strDrive = strDriveOld) and (strShare = strShareOld)
Next
if conDEBUG then WScript.Echo "bolAlreadyMapped = " & bolAlreadyMapped

if NOT bolAlreadyMapped then
' Remove mapping if it is already there (else mapping will fail)
objNetwork.RemoveNetworkDrive strDrive, TRUE, TRUE
err.clear

' Map thu pig
objNetwork.MapNetworkDrive strDrive, strShare, TRUE
If err.number = 0 then
strMsg = conScriptName & ": Mapped " & strDrive & " to " & strShare
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
else
strMsg = conScriptName & ": Err = " & err.number & "; " & err.description
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
WScript.Quit
End if
else
strMsg = conScriptName & ": No change, alread mapped " & strDrive & " to " & strShare
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
end if ' bolAlreadyMapped

' ============================================================
' The End
' ============================================================
strMsg = "END: " & conScriptName
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg

Set objNetwork = Nothing

Monday, June 19, 2006

UserOutlookEAS.vbs: Install EAS Outlook client

Author: Robert Lawson
Environment: Windows XP, Outlook , EAS, vb-script
Description: This installs the EAS client for Outlook users in a given Active Directory OU, if they are a member of an EAS group
. This script is run as Active Directory Group Policy log on script, and to make trouble shooting easier, all steps are written to application event log.
Code:
'=========================================================================
' VBScript Source File -- Created with XLnow OnScript
' FILE : UserOutlookEAS.vbs
' AUTHOR : Robert Lawson
' COMPANY: Soka University of America
' DATE : 6/19/2006 Robert Lawson Creation Date
' 11/20/2006 Robert Lawson Always do Outlook updates, improved on EAS logic
' 12/01/2006 Robert Lawson Added disable menu and remove pst references
' COMMENT: Manage EAS deployment: installing EAS client, and making Outlook setting
' conUpdateRegKeys controls if this will update registry keys (Outlook settings)
' Office 2003 only (Office Versions: 11.0 = 2003; 10.0 = XP)
' Registry keys are not setup by default by Outlook

'=========================================================================
option explicit
On Error Resume Next ' Required for reading registry
const conScriptName = "UserOutlookEAS.vbs"
const conDEBUG = FALSE
const conUpdateRegKeys = TRUE ' TRUE = will update Outlook reg keys

Dim strMsg, intLoc
Dim objShell, varTemp, bolRegKeyExists, varNewValue
Dim objFSO, objTS, objExecute
Dim bolOutlookInstalled, bolZantazClientInstalled, bolEASUser
Dim objNetwork, strUserName, strUserDomain, strGroupName, strComputerName
Dim strOU, strFilter, strQuery, rs, objCommand, UserADsPath, objUser, objConnection, objGroup, strKey

const conOutlookRegistryKey = "HKCU\Software\Microsoft\Office\11.0\Outlook\OutlookName"
const conOutlookDisableAutoArchiveKey = "HKCU\Software\Microsoft\Office\11.0\Outlook\Preferences\DoAging"
const conOutlookDisableCreatePSTfilesKey = "HKLM\SOFTWARE\Microsoft\Office\11.0\Outlook\DisablePST"
const conOutlookDisabledCmdBarKey = "HKEY_CURRENT_USER\Software\Policies\Microsoft\Office\11.0\Outlook\DisabledCmdBarItemsList"
const conZantazFile = "C:\Program Files\ZANTAZ\EAS Client\EASCOMPRESS.dll"
const conEASclient = "\\server3\Client\uniClient.msi"
const conRegKeyYes = 1
const conEASGroup = "EASUser"

' Window stype to run
const WINDOWHIDDEN = 0
const WINDOWNORMAL = 1
const WINDOWMINIMIZE = 2
Const ADS_SCOPE_SUBTREE = 2

' ============================================================
' Setup
' ============================================================
Set objShell = CreateObject( "WScript.Shell" )
Set objNetwork = Wscript.CreateObject("Wscript.Network")

set objConnection=Createobject("ADODB.Connection")
set objCommand=CreateObject("ADODB.Command")
objConnection.Provider="ADSDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

strMsg = "BEGIN: " & conScriptName
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg

' ============================================================
' Determine if EAS User (determined by AD group membership)?
' ============================================================
' Get User Info from Network log in
strComputerName = objNetwork.ComputerName
strUserName = objNetwork.UserName
strUserDomain = objNetwork.UserDomain
strMsg = conScriptName & " values: CN = " & strComputerName & "; UN = " & strUserName & "; DN = " & strUserDomain
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg

' Get User Active Directory information
bolEASUser = FALSE
strOU = "DC=uni,DC=edu"
strFilter = "sAMAccountName = " & "'" & strUserName & "'"
strQuery = "SELECT ADsPath FROM 'LDAP://" & strOU & "' WHERE " & strFilter

strMsg = conScriptName & ": LDAP strQuery = " & strQuery
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg

objCommand.CommandText= strQuery
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Set rs = objCommand.Execute
if rs.EOF or rs.BOF then
intLoc = 5
strMsg = conScriptName & ": Error @ " & intLoc & ". Unabled to get AD user for " & strUserName
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
else
' Verify if user is member of an EAS group
UserADsPath = rs.fields("ADsPath").value
Set objUser = GetObject(UserADsPath)

For Each objGroup In objUser.Groups
' sample: "CN=grpPeopleSoftDBTech"
strGroupName = objGroup.Name
if conDEBUG then Wscript.Echo strGroupName
bolEASUser = (instr(1,strGroupName,conEASGroup) > 0)
if bolEASUser then Exit For
Next
end if
strMsg = conScriptName & ": bolEASUser = " & bolEASUser
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg

' ============================================================
' Is Outlook installed for this computer user?
' ============================================================
varTemp = objShell.RegRead (conOutlookRegistryKey)
bolOutlookInstalled = (Err.number= 0)
if conDEBUG then Wscript.Echo " bolOutlookInstalled= " & bolOutlookInstalled

' ============================================================
' Is Zantaz EAS client installed on this computer? If not, do so
' ============================================================
set objFSO = CreateObject("Scripting.FileSystemObject")
bolZantazClientInstalled = (objFSO.FileExists(conZantazFile))
strMsg = conScriptName & ": bolOutlookInstalled = " & bolOutlookInstalled & "; conUpdateRegKeys = " & conUpdateRegKeys & _
"; bolZantazClientInstalled = " & bolZantazClientInstalled
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg

' Need to install EAS client?
if bolOutlookInstalled and Not bolZantazClientInstalled then
set objFSO = CreateObject("Scripting.FileSystemObject")
if (objFSO.FileExists(conEASclient)) then
objShell.Run conEASclient, WINDOWHIDDEN, True
if err.number = 0 then
strMsg = conScriptName & ": Installed successfully " & conEASclient
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
bolZantazClientInstalled = TRUE
else
intLoc = 10
strMsg = conScriptName & ": Error @ " & intLoc & " Num = " & Err.number & " " & Err.Description
DoError(strMsg) ' Failed to execute
end if
else
intLoc = 15
strMsg = conScriptName & ": Error @ " & intLoc & ". File does not exist " & conEASclient
DoError(strMsg) ' File does not exist
end if
end if

' ============================================================
' Update Outlook Registry Entries?
' ============================================================
if bolOutlookInstalled and conUpdateRegKeys then
' Disable auto archive features? 1=yes, 0=no (if no registry, treated as = 0)
varTemp = ""
varTemp = obJShell.RegRead(conOutlookDisableAutoArchiveKey)
bolRegKeyExists = (err.number = 0)
err.Clear
if Not bolRegKeyExists or (varTemp <> conRegKeyYes) then
objShell.RegWrite conOutlookDisableAutoArchiveKey, conRegKeyYes, "REG_DWORD"
if err.number = 0 then
strMsg = conScriptName & ": Updated registry " & conOutlookDisableAutoArchiveKey
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
else
intLoc = 20
strMsg = conScriptName & ": Error @ " & intLoc & " Num = " & Err.number & " " & Err.Description
DoError(strMsg) ' Failed to execute
end if
else
strMsg = conScriptName & ": Registry not updated, value already set for " & conOutlookDisableAutoArchiveKey
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
end if

' Disable creating any pst files? 1=yes, 0=no (if no registry, treated as = 0)
varTemp = ""
varTemp = obJShell.RegRead(conOutlookDisableCreatePSTfilesKey)
bolRegKeyExists = (err.number = 0)
err.Clear
if Not bolRegKeyExists or (varTemp <> conRegKeyYes) then
objShell.RegWrite conOutlookDisableCreatePSTfilesKey, conRegKeyYes, "REG_DWORD"
if err.number = 0 then
strMsg = conScriptName & ": Updated registry " & conOutlookDisableCreatePSTfilesKey
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
else
intLoc = 23
strMsg = conScriptName & ": Error @ " & intLoc & " Num = " & Err.number & " " & Err.Description
DoError(strMsg) ' Failed to execute
end if
else
strMsg = conScriptName & ": Registry not updated, value already set for " & conOutlookDisableCreatePSTfilesKey
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
end if

' Disable Outlook menu items KB309136
' TCID1 5575 Disable option to create a PST (File>New>Outlook Data File)
' TCID2 5576 Disable option to open a PST (File>Open>Outlook Data File)
strKey = conOutlookDisabledCmdBarKey & "\TCID1" ' Unique value for menu disable
varNewValue = "5575" ' Disable option to create a PST
objShell.RegWrite strKey, varNewValue, "REG_SZ"
if err.number = 0 or err.number = 500 then
err.Clear
strMsg = conScriptName & ": Updated registry " & strKey
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
else
intLoc = 25
strMsg = conScriptName & ": Error @ " & intLoc & " Num = " & Err.number & " " & Err.Description
DoError(strMsg) ' Failed to execute
end if

strKey = conOutlookDisabledCmdBarKey & "\TCID2" ' Unique value for menu disable
varNewValue = "5576" ' Disable option to open a PST
objShell.RegWrite strKey, varNewValue, "REG_SZ"
if err.number = 0 or err.number = 500 then
err.Clear
strMsg = conScriptName & ": Updated registry " & strKey
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg
else
intLoc = 30
strMsg = conScriptName & ": Error @ " & intLoc & " Num = " & Err.number & " " & Err.Description
DoError(strMsg) ' Failed to execute
end if
end if ' Registry Entry update

' ============================================================
' The End
' ============================================================
strMsg = "END: " & conScriptName
if conDEBUG then Wscript.Echo strMsg
objShell.LogEvent 0,strMsg

Set objNetwork = Nothing

' ======================================================
Function DoError(strErrMsg)
On Error Resume Next
Dim objShell

if conDEBUG then Wscript.Echo strErrMsg

Set objShell=CreateObject("wscript.shell")
objShell.LogEvent 1,strErrMsg
End Function

Sunday, December 25, 2005

UdriveSetup.cmd: Create network drive

Author: Robert Lawson
Environment: Windows Server, Active Directory
Description: This command is used to manually setup a network share for a user. This was used to test syntax and use of xcacls. Domain Admin membership required to run.
Code:
@ECHO OFF
rem file : UdriveSetup.cmd
rem purpose: setup network share drive
rem create : 25-dec-2005/r lawson
rem
rem notes
rem 1. Download xcacls from microsoft
rem 2. Follow setup from KB# 825751
rem 3. Change user name for 'edummy'
rem
rem UdriveSetup.cmd edummy \\server1\UserStore
rem UdriveSetup.cmd edummy c:\temp
SET THISCOMMAND=%0
SET LOGFILE=%TEMP%\UdriveSetup.log

:checkForHelp
@if /i [%1] == [-h] (goto usage)
@if /i [%1] == [/h] (goto usage)
@if /i [%1] == [-?] (goto usage)
@if /i [%1] == [/?] (goto usage)
@if /i [%1] == [-help] (goto usage)
@if /i [%1] == [/help] (goto usage)

:verifyParams
@if [%1] == [] (goto parameterError)
@if [%2] == [] (goto parameterError)
SET NEWDIRECTORY=%2\%1
goto verifyDirectory

:parameterError
@Echo %DATE% %TIME% FAILED: Not enough parameters>>%LOGFILE%
goto end

:verifyDirectory
rem @if /i NOT EXIST [%NEWDIRECTORY%] (goto Execute)
DIR %NEWDIRECTORY%>NUL
IF ERRORLEVEL 1 GOTO Execute
@Echo %DATE% %TIME% FAILED: Directory already exists>>%LOGFILE%
goto end

:usage
@echo Create a network U drive for a user
@echo
@echo Usage: %THISCOMMAND% [sAMAccountname] [UNC]
@echo
@echo [sAMAccountname] = user id
@echo [UNC] = Where to create directory using the sAMAccountname
@echo
pause
goto end

:Execute
MKDIR %NEWDIRECTORY%
rem remove the /Q to display
"%SystemRoot%\system32\cscript.exe" "%SystemRoot%\system32\xcacls.vbs" %NEWDIRECTORY% /O SOKA/%1 /I ENABLE /Q
@Echo %DATE% %TIME% SUCCESS: Directory created: %NEWDIRECTORY%>>%LOGFILE%

:end
ENDLOCAL

Tuesday, September 20, 2005

RmvOldComputers.bat: remove unused computer objects

Author: Robert Lawson
Environment: Windows Server, Active Directory
Description: This script runs nightly to remove Active Directory computer objects that have not been used in a 9 month period of time. Why 9 months? I think it is too long, but that's the guesstimate the longest time a student would be off-campus, including semester abroad. Removing the object effectively dis-joins computer from the AD domain. This also logs results to audit-log file... to help explain any issues.
Code:
rem File: RmvOldComputers.bat
rem
rem Purpose: Remove computers from domain older than 'x' weeks
rem
rem Author/Date: Robert Lawson/20-Sep-2005
rem
rem Notes:
rem 1. inactive is expressed in weeks (9 months = 36 weeks).
rem 2. computers that had shared printer will fail ("..is container and contains objects..")
rem
date/t>>C:\Temp\ListOldComputers.txt
dsquery computer "OU=Computer Accounts,DC=uni,DC=edu" -o rdn -limit 0 -inactive 36>>C:\temp\ListOldComputers.txt
rem
rem dsquery computer "OU=Computer Accounts,DC=uni,DC=edu" -limit 0 -inactive 36dsrm -noprompt -c -q