Logon Scripting

39
Logon Scripting Insert Instructors name Here

description

Logon Scripting. Insert Instructors name Here. The evolution of the logon script. In the past, we mapped everyone manually Used a simple how to pamphlet so the user could map themselves, but for some this was still difficult to follow - PowerPoint PPT Presentation

Transcript of Logon Scripting

Logon Scripting

Logon ScriptingInsert Instructors name Here1The evolution of the logon scriptIn the past, we mapped everyone manuallyUsed a simple how to pamphlet so the user could map themselves, but for some this was still difficult to followAfter hours of research, we began to discover and develop Batch filesAfter years of research, we began to use VBScript

2The evolution of the logon scriptWindows Server 2000 Vs Windows Server 20032000 did not have a GPO setting for the logon script, but it did have one for each user in ADUC. Problem was, when a person would hop sites, an admin would have to know about it and change the script setting. This was to much overhead, so we just had the user run the scripts on their own giving them simple instructions and a file path2003 did have the GPO setting for a user logon script, but due to legacy mindsets, it was not used and we used the old method, up until nowCurrently, we have a redirector script linked via GPO to every user in ADUC. This determines the subnet and runs a script associated with that subnet. The subnet script is managed by the site admin, while the redirector is managed by the enterprise admin. This allows for the site admin to choose how to script his site , what kind of script he will use and the enterprise admin just lays the groundwork to make that happen.

Utilities used for scripting:Text editors (notepad.exe)Text editors specifically built for scripts (Notepad ++)

3What we use scripts forSite logon Script is used to:To map network drives and network printersTo set basic environmental variables on the computer (WAVE radio settings, etc)Copy over files (mIRC settings)Add items to FavoritesChange HomepageRedirector script: A VBS script that replaces the need for a GPO set to a site for the logon scriptIt determines the subnet the user is in, then determines what site script to run based on the subnetTypes of scripts we useBatch Files (.bat)Visual Basic Scripts (.vbs)

4Components of a scriptRemarks: Remarks are used in scripts as place holder, descriptions of code and credits, among other things. It is text that is not read by the scripting engineVariables: a keyword or phrase that is linked to a value stored in the system's memoryUsed to store numeric values that can be changed, or text values that can also be changed or manipulated, or used in codeConstant: a special kind of variable whose value cannot be altered during program executionArray: a variable that can have multiple valuesExample, Variable(0) = "red", Variable(1) = "Blue"

5Components of a scriptProcedure: a portion of code with a larger program that performs a specific taskConditional Statements: a line of code that decides what code to execute based on a whether a statement is true or falseIfThen statementsCase StatementsLooping: a portion of code that continually executes until a certain condition is metCount till ten for exampleInput: a portion of code that prompts the user for inputOutput: a portion of code that is displays something for the user6

7

8SET Command and Windows Environmental VariablesUsing the SET command in DOS Prompt will display all the environmental variables in windows and what they are associated to.For Example, if you want to know what DC the computer is authenticating with, run the SET command and look through the list for logonserverUse in scriptsAll enviro. Variables in scripts are enclosed between 2 % signsEX %logonserver%You can use the variable names to determine things in your script. For example, if you want, in your script you can use an if statement to run code based on what logon server it hasBATCH ExampleIf %logonserver% EQU DC02 echo "Domain Controller 2"9Commonly used Enviro. Variables%COMPUTERNAME% - the computer name%LOGONSERVER% - the DC authenticating with%NUMBER_OF_PROCESSSORS% - number of processors on the system%ProgramFiles% - Program Files directory%USERDOMAIN% - Users domain%USERNAME% - Users name%windir% - Windows Directory10Batch FilesUsed to execute commands in DOS (usually pops up a DOS window)Echo: a command used to display text (output)to the user in the DOS window@echo off - when placed at the top of a batch file procedure, the batch does not display the lines of code to the user as it is being commanded in DOS UNLESS there is a specific call to @echo on will display the code as it is being commanded when placed at top of batch file procedure Echo Displays a message to the user in DOSEX: Echo This Text will display, echo will notRemarks: used to make remarks that will be disregarded by DOSREM is used to declare a remark in batch fileExample REM This is a remark11Batch filesNET USE: a command used to map a network drive or printerMap Network driveNET USE [driveletter:] \\Compname\share /persistent:No If Persistent is no, the drive will not remain mapped when the user logs off ExampleNET USE I: \\FS01.domain.net\Share /P:NoDisconnect driveNET USE [driveletter:] /deleteExampleNET USE I: /deleteMap printerNET USE lpt# \\PrintServer\Printer /Persistant:NoExampleNET USE lpt1 \\PS01.domain.net\printer1 /p:no

12Batch FilesGoto LabelUsed to jump to a portion of the batch procedure. The computer ignores the code between the Goto statement and the label it's being directed to when executedExampleGoto EndECHO Skipping this line:ENDECHO Done!13Batch FilesIF Command: Allows for the batch file to perform a conditional processIf EXIST used to determine if a file exist ExampleIF EXIST "C:\secfix.cmd" (ECHO Yes) ELSE (ECHO No)or IF EXIST "C:\secfix.cmd" (ECHO Yes) IF NOT EXIST "C:\secfix.cmd" (ECHO No) The "if" command can also be used to compare variablesComparing Variable commands:EQU - equalNEQ - not equalLSS - less thanLEQ - less than or equalGTR - greater thanGEQ - greater than or equalExample:IF %Number_of_Processors% EQU 2 (ECHO 2 Processors)14Other Batch file CommandsCLS : Clears the DOS screenEXIT: Exits DOSPAUSE: Pauses the batch file till user presses any key to continueCALL: used to run another batch file within a batch file. When the batch file that is called is completed, the remainder of the original batch file is completed. Note if the batch file does not exist it will give an error message.15Putting a batch file togetherCLS REM This is an example of a more complex batch file@echo offECHO This will map your printers and drives for your locationPauseCLSIF %LOGONSERVER% EQU \\DC02 (Goto LabDC02)IF %LOGONSERVER% EQU \\DC03 (Goto LabDC03) ELSE (goto LabError):LabDC02IF EXIST H: (NET USE H: /DELETE)NET USE y: \\fs01.domain.net\share/P:no NET USE lpt2 \\ps01.domain.net\printer /p:noGoto End:LabDC03 IF EXIST I: (NET USE I: /DELETE)NET USE I: \\FS02.domain.net\Share /P:noNET USE lpt3 \\ps02.domain.net\printer /p:noGoto End:LabErrorECHO I'm sorry, your Domain Controller is not defined. Please notify your site admin.Pauseexit:EndECHO your printer and network drive is mapped pauseExit16PE: Build and test a working Batch FileUsing the above batch file, build a batch file using your domain's environmental variables and map a printer and a network drive based on those variables.17Visual Basic Scripts (VBS)VBScripts give the script more functionality than the Batch files, but can be more difficult to write and more difficult to troubleshoot. Most of the same concepts are used in Vbscript, however the language itself can be differentRemarks: All remarks are designated with a ' markExample:' This is a remarkWscript.echo: Used to open a message box with output for the userExample:wscript.echo "This is a message using wscript.echo"

18VBScript: Setting VariablesVariables are used for a variety of task. They can be changed through out the script and displayed in output or be used to determine what to do next in the script when used with other code. But, you must first define a variable to use it. Example of a string Variable:strName = "Johnny"Example of an interger Variable:intNumber = 1Example of variables being changed intNumber = intNumber + 1' intNumber is now 2strName = strName &" Doomsday" 'strName is now Johnny Doomsday, the & is used in front of new textwscript.echo strName &" "&intNumberwscript.quit 'Quits the script19VBScriptConstants are variables that don't get changed in a scriptExample: Const unchangable = 1Set Arrays To declare an array, you must first declare the variable name and the number of "compartments" for the arrayDim cars(2)cars(0)="Volvo"cars(1)="Saab"cars(2)="BMW"Quitting the scriptTo end the script, you can simply let the script run to the end of the script and it will stop, or you can put the following command in where you want it to endwscript.quit

20VBScript: If ThenIf, Then, Else Statements: This statement can be placed on one line or encompass a number of lines of code.When multiple lines are used, an "end if" statement needs to be usedExample of single line:intValue = 4If intValue = 4 Then wscript.echo "four"Example of a multiple lineintValue = 4If intValue = 4 Thenwscript.echo "four"Elseif intValue = 5 Thenwscript.echo "five"Elsewscript.echo "Not five or four"End ifComparing Variable commands:= - equal - not equal< - less than - greater than>= - greater than or equal

21VBScript: Case StatementsCase statements act a lot in the same way that If Then statements do, BUT, the scripting engine does not read the parts of the case statement that does not pertain to the particular case. In an if then, it still reads it, but it just does not execute. So, it makes the script run faster.ExampleintValue = 4Select Case intValueCase 4wscript.echo "Four"Case 5wscript.echo "Five"Case Elsewscript.echo "not Five or Four"End Select22VBScript: LoopsFor Next Loops -operate till a condition is metExample (will end the loop when I = 5)for I = 0 to 5wscript.echo "Number " & InextFor Each loops operates till each value in an array has been addressedDim cars(2)cars(0)="Volvo"cars(1)="Saab"cars(2)="BMW"

For Each x In cars wscript.echo xNext

23VBScript: LoopsDo While Loops: loops through code until a condition is metExample i=0Do While i < 10 wscript.echo i i=i+1Loop24VBScript: Delete Network PrintersA networked printer over a WAN link will slow down a computer system. It is important to try and delete these printers before mapping any new ones. Here's the code to do it

Set objNetwork = CreateObject ("Wscript.network")Set objPrinter = objNetwork.enumprinterconnectionsPrinterflag=falseFor I = 0 to objPrinter.count -1 Step 2 if left(objPrinter.item(i+1), 2) ="\\" Thenon error resume nextobjNetwork.RemovePrinterConnection objPrinter.item(i+1)on error Goto 0 End ifNext25VBScript: Mapping a printerFirst, set the network script variable object Set WshNetwork = CreateObject("WScript.Network")Next, you add the printer and define the drivers usedWshNetwork.AddWindowsPrinterConnection "\\PS01.domain.net\printer", "HP LaserJet 1200 Series PCL" You can then set the printer as a default printer WshNetwork.SetDefaultPrinter "\\PS01.domain.net\printer"26VBScript: Remove Network DrivesIn a logon script, it is important to unmap all network drives prior to mapping the new ones. Reason being, a mapped network drive over a WAN link slows down the user computer. 'Dim wshNetworkSet wshNetwork = CreateObject("Wscript.network")Dim bForce, bUpdateProfilebForce = TruebUpdateProfile = TrueOn Error Resume Next ' Prevents the user from seeing an error if drive doesn't existDo this code for every letter in the alphabet above F WshNetwork.RemoveNetworkDrive "Z:", bForce, bUpdateProfileDisable the error handlers current positionOn Error GoTo 0 'resets error handling

27VBScript: Map Network DrivesMapping network drives is a lot like in a batch file, but different languagewshNetwork.MapNetworkDrive [driveletter:], "\\compname\share", [pers T or F]Example:Set wshNetwork = CreateObject("Wscript.Network")wshNetwork.MapNetworkDrive "I:", "\\FS01.domain.net\Share", true 28VBScript: Registry EntriesFor some programs, specific registry values are defined that can be changed by VBScript. For example, we can update the Wave server, username and password with the appropriate values for a site using this method so the user doesn't have to know itSet the code variablesstrComputer = "."Const HKEY_CURRENT_USER = &H80000001 Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ strComputer & "\root\default:StdRegProv")Set Registry ValuesCreate the key pathoReg.CreateKey HKEY_CURRENT_USER,RegRunValPathoReg.CreateKey HKEY_CURRENT_USER, "Software/Yoursite"Create the key and set the valueoReg.SetStringValue HKEY_CURRENT_USER,RegRunValPath,RegRunValName,strValueoReg.SetStringValue HKEY_CURRENT_USER, "Software/Yoursite", "Key Name", "Cat

Get Registry ValuesoReg.GetStringValue HKEY_CURRENT_USER,RegRunValPath,RegRunValName,strValueoReg.GetStringValue HKEY_CURRENT_USER,"Software/Yoursite", "Key Name", strValuewscript.echo strValue

Value in this code of strValue is "Cat"29VBScript: Copy Objects Some programs use INI files to store information usually stored in the registry. Others have their own proprietary databases. You can use a script to copy these files from a network share to a persons computer

Const OverwriteExisting = TRUESet objFSO = CreateObject("Scripting.FileSystemObject")objFSO.CopyFile "\\fs01.domain.net\hidden$\your.ini", "C:\Program" & _ " Files\YourProg\your.ini", OverwriteExisting

'the & _ allows you to break a long line of code and continue it on to a new line strictly to make it look better in the text file 30VBScript: Add a favorite You can also add a favorite URL to the favorite menu in IE

Const ADMINISTRATIVE_TOOLS = 6Set objShell = CreateObject("Shell.Application")Set objFolder = objShell.Namespace(ADMINISTRATIVE_TOOLS) Set objFolderItem = objFolder.Self

Set objShell = WScript.CreateObject("WScript.Shell")strDesktopFld = objFolderItem.Path

Set objURLShortcut = objShell.CreateShortcut(strDesktopFld & "\W3 Schools.url")objURLShortcut.TargetPath ="http://www.w3schools.com"objURLShortcut.Save31Vbscript: User inputPrompting a user with a yes or no questionFirst declare a constant or variable with a window titleconst POPUP_TITLE="Your Printers and Drives"Setup a new variable to define a shell object (helps to simplify the code)Set objshell = wscript.createobject("wscript.shell")Create new variable that receives user input from the yes/no popup that pops upiRetVal = objshell.popup("Would you like to setup your computer to the default" & _ " settings for Your Site?", 10, POPUP_TITLE, vbquestion + vbyesno)' at the end of a line of code, the & _ will allow you to continue the line of code on the next line. This is done mainly for the appearance of the code and make it easier to read for the author32VBScript: User InputYou can also get a text from the user placed in a variableVariable = InputName("your Text", "Box Title", Default, Vert Pos, Horz Pos)strUserInput = inputbox("Please enter your name:", "Name","Your name here", 300, 400)

Wscript.echo strUserInput33VBScript: Odds and endsRun a program or other fileSet objShell= CreateObject("Wscript.Shell")objShell.run "C:\yourprog.exe"Sets then retrieves info in ADUC (for a computer)Set objSysinfo = CreateObject("ADSystemInfo")

Set objComputer = GetObject("LDAP://" & objsysinfo.computername)objComputer.put "Description", "Your Desc"objComputer.Setinfo

wscript.echo objComputer.get("Description")34VBScript: Odds and endsSet Homepage (Internet Explorer)

Const HKEY_CURRENT_USER = &H80000001strComputer = "."Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ strComputer & "\root\default:StdRegProv")

strKeyPath = "Software\Microsoft\Internet Explorer\Main"oReg.CreateKey HKEY_CURRENT_USER,strKeyPath

strValueName = "Start Page"strValue = "http://blogs.technet.com/b/heyscriptingguy/"oReg.SetStringValue HKEY_CURRENT_USER,strKeyPath,strValueName,strValue

35VBScript: Odds and endsRetrieve system informationComputer Distinguished nameSet objSysinfo = CreateObject("ADSystemInfo")wscript.echo objsysinfo.computername

Model NumberstrComputer = "."Set objWMIService = GetObject(_ "winmgmts:\\" & strComputer & "\root\cimv2")set colitems=objWMIservice.Execquery("Select * from win32_Computersystem",,48)

for each objItem in colItemsModelNum = objitem.modelwscript.echo ModelNum Next36VBScript: Odds and endsSerial NumberstrComputer = "."Set objWMIService = GetObject(_ "winmgmts:\\" & strComputer & "\root\cimv2")set colitems=objWMIservice.Execquery("Select * from win32_BIOS",,48)

for each objItem in colItemsSerialNum = trim(objitem.serialnumber)wscript.echo SerialNumNext

37VBScript: Putting it all together' This is an example of a simple VBS Script'Prompt user to run the script of notconst POPUP_TITLE="Your Printers and Drives" Set objshell = wscript.createobject("wscript.shell") iRetVal = objshell.popup("Would you like to setup your " & _"computer to the default settings for Your Site?", _ ,POPUP_TITLE,vbquestion + vbyesno) If iRetVal = vbNo THEN wscript.quit if iRetVal = vbYes Then

' Delete all network printersSet objNetwork = CreateObject ("Wscript.network")Set objPrinter = objNetwork.enumprinterconnections

Printerflag=false

For I = 0 to objPrinter.count -1 Step 2 if left(objPrinter.item(i+1), 2) ="\\" Thenon error resume nextobjNetwork.RemovePrinterConnection objPrinter.item(i+1)on error Goto 0 End ifNext

'Map a printerSet WshNetwork = CreateObject("WScript.Network")WshNetwork.AddWindowsPrinterConnection "\\PS01.domain.net\printer", "HP LaserJet 4350 PCL 6" WshNetwork.SetDefaultPrinter "\\PS01.domain.net\printer"

'Map Network Drive Set wshNetwork = CreateObject("Wscript.Network") wshNetwork.MapNetworkDrive "I:", "\\PS01.domain.net\share", trueEnd ifWscript.echo "Your printer and drive is now mapped"Wscript.quit38PE: VBScriptUsing the above script, put together a script that maps a printer and a drive. For extra credit, try to map drives and printers based on the DC (may have too google how to find the logon server in VBS)

39