Vbscript Users Logon Script for Active Directory


This script as some pre-requisites that must be checked before.

1 – all folders and shares must be created

2 – all groups in ad must be created and associate to users

3 – this script must be associated to an Group policy object at logon scripts configuration option

4 – All network printers must be configured

5 – This script was developed to an implementation of Active directory where organization units where the base of the structure of Ou’s and groups.

To start let’s avoid that user call reporting an error.

on error resume next

Let’s go to the what matters

DIM WshNetwork, WshShell, oDrives, fso, fUserName, oGroupDict, arrGroupList
DIM Server, fuser, fComputername, fDomain, uo, scriptLogName
SET WshNetwork = WScript.CreateObject("WScript.Network")
SET WshShell   = WScript.CreateObject("WScript.Shell")
SET oDrives    = WshNetwork.EnumNetworkDrives
SET fso        = WScript.CreateObject("Scripting.FileSystemObject")
fComputername  = WshShell.ExpandEnvironmentStrings("%COMPUTERNAME%")
fUser          = WshNetwork.UserName
fDomain        = WshNetwork.UserDomain
fTMP           = WshShell.ExpandEnvironmentStrings("%TEMP%")
fWIN           = WshShell.ExpandEnvironmentStrings("%windir%")
Server  = "\\yourservername\"    ' Print Server and file Server
ScriptLogName  = fUser & "_" & date() & ".log"
SET inputFile  = fso.OpenTextFile(Server & "LOG\" & ScriptLogName, 8, TRUE)    ' logging file and location

Functions that will allow us to create shares, map drives, add printers, ……

    ' ----------------------------------------------------------
    ' Function for mapping drives
    ' ------------------------------------------------------------
SUB DriveMapper(Drive, Share)
    FOR i = 0 TO oDrives.Count -1 STEP 2
        IF LCase(Drive) = LCASE(oDrives.Item(i)) THEN
            IF NOT LCASE(Share) = LCASE(oDrives.Item(i+1)) THEN
                WshNetwork.RemoveNetworkDrive Drive, TRUE, TRUE
            ELSE
                inputFile.Write("-      Mapping")
                inputFile.Write("  -     SUCESS :  """ & Drive & """ to share """ & Share)
                inputFile.WriteLine("")
                EXIT SUB
            END IF
        END IF
    NEXT
    ON ERROR RESUME NEXT
    WshNetwork.MapNetworkDrive Drive, Share
        IF Err.Number = 0 THEN
            inputFile.Write("-      Mapping Drives")
            inputFile.Write("  -     SUCESS :  """ & Drive & """ to share """ & Share)
            inputFile.WriteLine("")
        ELSE
            inputFile.Write("-      Mapping Drives")
            inputFile.Write("  -     FAILED  :  """ & Drive & """ to share """ & Share)
            inputFile.WriteLine("")
        END IF
    ON ERROR GOTO 0
END SUB
    ' ------------------------------------------------------------
    ' Function Add Printer
    ' ------------------------------------------------------------
SUB AddPrinter(PrinterUNC)
    inputFile.Write("-      Add Printers")
    ON ERROR RESUME NEXT
    IF (fComputername = "TERMINALSERVER") THEN
        inputFile.Write("  -     FAILS")
        inputFile.WriteLine(NOW() & ": FAIL : Printer connection skipped because of server " & fComputername)
    ELSE
        WshNetwork.AddWindowsPrinterConnection Server & PrinterUNC
        IF Err.Number = 0 THEN
            inputFile.Write("  -     SUCESS - " & PrinterUNC)
            inputFile.WriteLine("")
         ELSE
            inputFile.Write("  -     FAILED  -  " & PrinterUNC)
            inputFile.WriteLine("")
        END IF
    END IF
    ON ERROR GOTO 0
END SUB
   ' --------------------------------------------------------------------
    ' Function to remove printers
    ' -----------------------------------------------------------------
SUB RemovePrinter(PrinterUNC)
    inputFile.Write("-      IMPRESSORAS REMOVER")
    SET oPrinters = WshNetwork.EnumPrinterConnections
    FOR i = 0 TO oPrinters.Count - 1 STEP 2
        IF UCASE(oPrinters.Item(i+1)) = UCASE(PrinterUNC) THEN 
            ON ERROR RESUME NEXT
            WshNetwork.RemovePrinterConnection Server & PrinterUNC, TRUE, TRUE
            IF Err.Number = 0 THEN
                inputFile.Write("  -     SUCESSO - Remove printer: " & PrinterUNC)
                inputFile.WriteLine("")
            ELSE
                inputFile.Write("  -     FALHA  -  Remove printer: " & PrinterUNC)
                inputFile.WriteLine("")
            END IF
            ON ERROR GOTO 0
            EXIT SUB
        END IF    
    NEXT
    inputFile.Write("  -     FAIL  -  Remove printer: " & PrinterUNC & " (Printer did not exist)")
    inputFile.WriteLine("")
END SUB
    ' ------------------------------------------------------------------------------------------------------------------
    ' Function to set default printer
    ' ------------------------------------------------------------------------------------------------------------------
SUB SetPrinterDefault(PrinterUNC)
    inputFile.Write("-      IMPRESSORAS PRE-DEFENIR")
    ON ERROR RESUME NEXT
    IF (fComputername = "TERMINALSERVER") THEN
        inputFile.WriteLine("TERMINALSERVER Client - SUCESS - Not added" & fComputername)
    ELSE
        WshNetwork.SetDefaultPrinter Server & PrinterUNC
        IF Err.Number = 0 THEN
            inputFile.Write("  -     SUCESS - Set as Default: " & PrinterUNC)
            inputFile.WriteLine("")
         ELSE
            inputFile.Write("  -     FAIL  -  Set as Default: " & PrinterUNC)
            inputFile.WriteLine("")
        END IF
    END IF
    ON ERROR GOTO 0
END SUB
    ' ------------------------------------------------------------------------------------------------------------------
    ' This function checks to witch groups users are member
    ' ------------------------------------------------------------------------------------------------------------------
Function IsMember(sGroup)
    DIM sAdsPath, oUser, oGroup
    IF IsEmpty(oGroupDict) THEN
        SET oGroupDict         = CREATEOBJECT("Scripting.Dictionary")
        oGroupDict.CompareMode = vbTextCompare
        sAdsPath  = WshNetwork.UserDomain & "/" & WshNetwork.UserName
        SET oUser = GETOBJECT("WinNT://" & sAdsPath & ",user")
        FOR EACH oGroup IN oUser.Groups
            oGroupDict.Add oGroup.Name, "-"
        NEXT
        SET oUser = NOTHING
    END IF
    IsMember = CBOOL(oGroupDict.Exists(sGroup))
    IF (IsMember) THEN
        inputFile.WriteLine("")
        inputFile.WriteLine("Group member: " & sGroup)
        inputFile.WriteLine("")
    END IF
End Function
    ' ------------------------------------------------------------------------------------------------------------------
    ' function that detects wich user is making login                    
    ' ------------------------------------------------------------------------------------------------------------------
SUB PutEnv(strName, strValue)
    inputFile.WriteLine("-      Username")
    DIM sh, env
    SET sh       = CREATEOBJECT("WScript.Shell")
    SET env      = sh.Environment("USER")
    env(strName) = strValue
        inputFile.WriteLine("  -     SUCESS - Set user variable """ & strName & """ to: """ & strValue & """")
        inputFile.WriteLine("")    
    sh  = EMPTY
    env = EMPTY
END SUB
    ' ------------------------------------------------------------------------------------------------------------------
    ' Function to create shortcut
    ' ------------------------------------------------------------------------------------------------------------------
SUB CreatShortcut(ShortCutName, ShortCutTarget, ShortCutLocation)
    inputFile.Write("-      shortcut")
    DIM MyShortcut, MyDesktop, DesktopPath
    DesktopPath           = WSHShell.SpecialFolders(ShortCutLocation)
    SET MyShortcut        = WSHShell.CreateShortcut(DesktopPath & "\" & ShortCutName)
    MyShortcut.TargetPath = WSHShell.ExpandEnvironmentStrings(ShortCutTarget)
    MyShortcut.Save
    ON ERROR RESUME NEXT
    IF Err.Number = 0 THEN
            inputFile.Write("  -     SUCESS - ShortCut " & ShortCutName)
            inputFile.WriteLine("")
    ELSE
        inputFile.Write("  -     FAIL - ShortCut " & ShortCutName)
        inputFile.WriteLine("")
    END IF
    ON ERROR GOTO 0
END SUB
    ' -------------------------------------------------------------
    ' To write in log
    ' -----------------------------------------------------
SUB WriteLog(strEntry)
    inputFile.WriteLine("Log:     " & strEntry)
END SUB

The general Functions Ended, now lets use them, some procedures were created

    ' ------------------------------------------------------
     ' mapping drives
     ' ----------------------------------------------------------
 SUB mapuser
 DriveMapper "m:", Server & "users\" & fUser ' for each user a folder must exist
 'CreatShortcut "networkusersfolder M -" & fuser &".lnk", "m:\", "Desktop"
 END SUB
 SUB mapo
 DriveMapper "o:", Server & "uo\general"     'this folder must exist        
 CreatShortcut "Network Share O.lnk", "o:\", "Desktop"
 END SUB
' ----------------------------------------------------------------------
 ' mapping drive n accord orgaorganization unit
 ' ---------------------------------------------------------------
SUB mapuo
 DriveMapper "n:", Server & "uo\" & uo
 END SUB
 ' ------------------------------------------------------------------------------------------------------------------
 ' Office shortkuts
 ' ------------------------------------------------------------------------------------------------------------------
 SUB addoffice
 CreatShortcut "Excel.lnk", "C:\Programas\Microsoft Office\OFFICE11\excel.exe", "Desktop"
 CreatShortcut "Word.lnk", "C:\Programas\Microsoft Office\OFFICE11\winword.exe", "Desktop"
 CreatShortcut "Outlook.lnk", "C:\Programas\Microsoft Office\OFFICE11\OUTLOOK.EXE", "Desktop"
 CreatShortcut "Access.lnk", "C:\Programas\Microsoft Office\OFFICE11\msaccess.EXE", "Desktop"
 END SUB
 ' ------------------------------------------------------------------------------------------------------------------
 ' windows explorer shortkut
 ' ------------------------------------------------------------------------------------------------------------------
 SUB addexplorador
 CreatShortcut "Explorador do Windows.lnk", "C:\WINDOWS\explorer.exe", "Desktop"
 END SUB
Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
 Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & fComputername & "\root\cimv2")
 Set colOperatingSystems = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")

Now is time to finally start the workstation configuration

' ------------------------------------------------------------------------------------------------------------------
 '                 Start Workstation configuration
 ' ------------------------------------------------------------------------------------------------------------------
inputFile.WriteLine("")
 inputFile.WriteLine("-                        " & NOW())
 inputFile.WriteLine("-                        User :  " & fuser)
 inputFile.WriteLine("-                        Computer :" & fComputername)
 For Each objOperatingSystem in colOperatingSystems
 dtmConvertedDate.Value = objOperatingSystem.InstallDate
 dtmInstallDate = dtmConvertedDate.GetVarDate
 inputFile.WriteLine("        " & objOperatingSystem.Caption & " SP" & objOperatingSystem.ServicePackMajorVersion  & " Version " & objOperatingSystem.Version & " installed in " & dtmInstallDate)
 Next
 inputFile.WriteLine("-    Configure Printers")

You can see next some examples to configure printers, mapping drives and create short cuts
users must be member of finance or markting global groups

' ------------------------------------------  Member Finance group
IF isMember ("Finance") THEN
    AddPrinter "PRINTER04"
    AddPrinter "PRINTER07"
    AddPrinter "PRINTER11"
    addoffice
    uo = "finance"
    mapuo
    addexplorador
END IF
' ------------------------------------------  Member markting group
IF isMember("Markting") THEN
    AddPrinter "PRINTER02"
    AddPrinter "PRINTER03"
    addoffice
    uo = "markting"
    mapuo
    addexplorador
END IF

The end of script

inputFile.WriteLine("____________________________________________")
inputFile.WriteLine("")
inputFile.WriteLine("-                        Configuration END")
inputFile.WriteLine("____________________________________________")

That’s it

Hope that this script can be useful, Feel free to rate and comment, and thank you for visiting my blog and read this post.

Advertisements

About rodvars
Been working in IT Services/Consulting for the past 15 years. My main areas of work are planning, development, managing and administration System infrastructures focusing on optimizing user processes, enforcing business security, performance enhancements, high availabilty and infrastucture scalability.

6 Responses to Vbscript Users Logon Script for Active Directory

  1. rodinhas2 says:

    Great post Rodolfo.Very useful Vbs. Thks

  2. lv bag says:

    Pretty great post. I simply stumbled upon your weblog and wanted to say that I’ve really enjoyed browsing your blog posts. After all I’ll be subscribing to your feed and I’m hoping you write once more very soon!

  3. Wonderful advice. Lucky me I ran across your web site by accident. I’ve book-marked it for some other occasion!

  4. Toby says:

    I actually was basically looking for plans for my very own blog site and observed your own article, “Vbscript Users Logon
    Script for Active Directory | My Knowledge
    Base” Windows Blinds , would you care in cases where I actually start using a handful of of your ideas?
    With thanks -Chong

    • rodvars says:

      That would be very interesting to have your feedback about the real situations where my blog was usefull.
      you also have my e-mail rodvars@gmail.com that you can use for ask any question you have.

  5. Marvelous, what a website it is! This webpage provides helpful information to
    us, keep it up.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: