Documents
Resources
Learning Center
Upload
Plans & pricing Sign in
Sign Out

WinAdminToolKit.doc - Illinois Technology Conference

VIEWS: 242 PAGES: 47

									                                                                        Page 1


    Tech Coordinator Feast
                                         2006
           Belleville Session
                   July 24-26, 2006


        Network Administrator‟s Toolkit
               Scripting Basics
                     with
        „samples & partial explanations‟

"The first 90% of the code accounts for the first 90% of the development
time. The remaining 10% of the code accounts for the other 90% of the
development time." -Tom Cargill of Bell Labs circ. 1980

     Terry Sullivan                                      Jim Pattenaude
     Technology Director                                 Technology Director
     Shiloh CUSD #1                                      Marshall CUSD C2
     tsulliva@comwares.net                         jpattenaude@marshall.k12.il.us




                    Last Edited on July 22, 2006
                                                                                                   Page 2
Where can scripts be set to AutoRun?
      Active Directory – User – Profile – Logon Script
      Active Directory – OU - GPO / User Policy
      Active Directory – OU - GPO / Computer Policy
      Local Machine – All User – Start Menu – Startup
      Local Machine – Registry – use the RUN key
       o       Local Machine – Software – Microsoft – Windows – Current Version – Run
      Local Machine – use the task scheduler

                                                  Deploying Scripts:
Using Local Machine All User Start Menu
You can also place the script in the Documents and Settings\All Users\Start Menu\Program Files\Startup folder on
the client computer. (will run using the local user “rights”)

Using Local Machine Registry – AutoRun
Make a folder c:\scripts and copy needed scripts here. Then edit the registry to autorun the desired script. Enter the
path and filename of the script in the appropriate registry key

Using Active Directory User Profile
Right Click on the user and select Properties. Click on the Profile tab and type the name of the script that you want
to run. These scripts should be stored in the NETLOGON Share

Using Windows GPO’s

User Policy  Using the Group Policy Object Editor
       Use Logon or Logoff scripts.
             User Configuration
                     Windows Settings
                            Scripts (Logon/Logoff)
             Double click on the script that you would like to use on the right.
             Click the Add button and brows for the script.

Computer Policy  Use Startup or Shutdown scripts
             Computer Configuration
                     Windows Settings
                            Scripts (Startup/Shutdown)
             Double click on the script that you would like to use on the right.
             Click the Add button and brows for the script
             Caveat – running scripts per computer rather than per user may need the LoopBack policy enabled
             Example - Steps needed to run a script for an OU containing computers to install printers.
             1. Create and OU for the computers that you want to install the printers.
             2. Create a new GPO on this OU
             3. Drill down into the new GPO to Computer configuration | Administrative Templates | System
     |Group Policy | User Group Policy loopback processing mode and specify it to be MERGE mode.

Next add the script for the printers.
Drill down to User Configuration | Windows Settings | Scripts | Logon
Click the Add to add the script.


                                    Last Edited on July 22, 2006
                                                                                             Page 3
So What’s a Script?
From Guy’s Computer Performance:
    http://www.computerperformance.co.uk/Logon/logon_scripts.htm

   Jobs that a script can do

   Windows Script Host provides objects for manipulation of your scripts. Here are some of the tasks that
   these objects and services can do for you:

             Map network drives
             Connect to printers
             Modify environment variables e.g. Temp
             Run basic functions such as CreateObject and GetObject
             Print a message to a Message Box on screen
             Modify keys and values in the registry

   The big picture of the scripting model

   There are three layers in the script model.

             Top Layer: ActiveX, COM, DLL's (You have to know your boundaries so I won't go any further
             into ActiveX)
             Middle Layer: Script Engines VBScript, and JSCript (Equivalent of .bat files)
             Bottom Layer: WSH with :CSCript, WSCript, NWSCript also IE Explorer (Equivalent of DOS or
             CMD.exe)

   So what is a Script?

   A Windows 2003 script is a program written in a special language called VBScript or JScript. (If you
   prefer you could use Perl or Rexx) These scripting languages are designed to create short applications
   that provide quick solutions to network problems.

   Different Types of Scripts

            .vbs - VBScript files WSH
            .js - JScript files for WSH
            .wsf - Project file, container object for WSH files
            .bat or .cmd - DOS batch files
            .html - Familiar 'mark-up' language.
            .asp - Active Server Pages for webs

   What is WSH? (Windows Scripting Host)

   Windows Scripting Host is aptly named, think of WSH as providing a greenhouse where scripts can
   flourish. When a logon script arrives from the server, WSH makes sure objects and services are available
   for the script. It also check security and passes the script to the appropriate script engine. Example
   engine: ActiveX.

   WSH is ideal for non-interactive scripting jobs, such as logon configuration, administrative scripting, or
   machine automation.

   Versions of WSH
                               Last Edited on July 22, 2006
                                                                                         Page 4
Windows 2003 and XP have version 5.6; while Windows 2000 and ME have version 2.0. If you have
Windows 95, 98, or Windows NT 4.0, then you have version 1.0. The actual executables are
WSCRIPT.exe and CSCRIPT.exe. To check your version     Start, Search, WSCRIPT, right click,
properties, version.

Terminology Check

  Script - Commands written instruction is special language VBScript or JScript
  Windows Scripting Host - WSH is the part that reads and carries out the instructions in the script
  WSCRIPT and CSCRIPT - Executables that actually interpret the .vbs or .js script files




                            Last Edited on July 22, 2006
                                                                                                     Page 5
Windows Scripting Basics
Shell Processor – (command prompt)
     Utilities
     Batch files
     Login Scripts
Windows Scripting Host (WSH)
     Interpreted
     Object Language – based on Visual Basic
Jscript
     Interpreted
     Object Language – based on Java
Other – have to install the language interpreter (most are free)
     Perl
     Python
     Rexx

Windows Scripting Host (Wscript.exe)
    Object Language
    VBS code at first appears strange or busy. It seems to require a lot of commands to complete a minimal task
    Object Model
          o Based on tools or “objects” and actions or “methods”
                    Example
                          FileSystemObject
                                  o CopyFile
                                  o DeleteFile
                                  o FileExists
                                  o MoveFile
                                  o CopyFolder
                                  o DeleteFolder
                                  o FolderExists
                                  o MoveFolder
          o Uses dotted notation to connect an action to an object
                    object.method ( example FSO.CopyFile )
    Best practice programming
          o Need to declare all variables (Dim variable)
          o Need to code variable types (object, integer, string, etc.)
          o Need to “instantiate” objects, basically declare and assign variable
                    Dim oFSO
                    Set oFSO = CreateObject("Scripting.FileSystemObject")
                    oFSO.CopyFile “source file” “destination”
          o Should initialize variables (Set variable = …)
          o Should release variable when done (Set variable = Nothing)
          o Should error trap
          o Should use comments to document




                                      Last Edited on July 22, 2006
                                                                                                    Page 6
Classic Batch or Command File
REM ====================================================================
REM BATCH FILE to Turn off XPsp2 Firewall, Schedule Shutdown, & UNInstall local PaperCut software
REM create local group, reset local admin, confirm Network Config
REM used Dec 2005 during winter break
REM ===================================================================
cls
echo off
echo.
echo -------------------------------
echo Configuring XP SP2 Firewall
echo -------------------------------
echo.
netsh firewall set opmode DISABLE
echo.
echo.
echo -------------------------------
echo Building Local Management Groups
echo -------------------------------
call \\Srvw2k301\Scripts\Utility\LocalAdmin.vbs
call \\Srvw2k301\Scripts\Utility\LocalUser.vbs
echo.
echo -------------------------------
echo Rebuilding Shutdown Schedule
echo -------------------------------
echo.
at /delete /yes

VER | FIND /I "2000"
IF %ERRORLEVEL%==0 at 22:00 /every:monday,tuesday,wednesday,thursday,friday shutdown /c /r
VER | FIND /I "2000"
IF %ERRORLEVEL%==0 copy \\Srvw2k301\Scripts\Utility\shutdown.exe c:\winnt\system32

VER | FIND /I "XP"
IF %ERRORLEVEL%==0 at 22:00 /every:monday,tuesday,wednesday,thursday,friday shutdown -f -r

echo.
echo -------------------------------
echo Removing LOCAL PaperCut Printjob Counter
echo -------------------------------
echo.
call "C:\Program Files\PaperCut\unins000.exe"
echo.
pause
echo.
echo -------------------------------
echo Confirm the IP Address information
echo Add the MAC address to the inventory database
echo -------------------------------
echo.
ipconfig /all
pause
echo.
echo -------------------------------
echo System should now be updated. If you have all your notes recorded,
echo logout and proceed to the next workstation
echo -------------------------------
echo.
pause
exit
                                       Last Edited on July 22, 2006
                               Page 7




Last Edited on July 22, 2006
                                                                                                                    Page 8
Task scheduler utilities
AT command  older scheduler service
The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule
service must be running to use the AT command.

AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
AT [\\computername] time [/INTERACTIVE] [ /EVERY:date[,...] | /NEXT:date[,...]] "command"

       \\computername Specifies a remote computer. Commands are scheduled on the local computer if this parameter is
        omitted.
       id            Is an identification number assigned to a scheduled command.
       /delete         Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are
        canceled.
       /yes            Used with cancel all jobs command when no further confirmation is desired.
       time            Specifies the time when command is to run.
       /interactive     Allows the job to interact with the desktop of the user who is logged on at the time the job runs.
       /every:date[,...] Runs the command on each specified day(s) of the week or month. If date is omitted, the current day
        of the month is assumed.
       /next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date
        is omitted, the current day of the month is assumed.
       "command"           Is the Windows NT command, or batch program to be run.

SCHTASK command – NEW to XP and Server 2003
Description: Enables an administrator to create, delete, query, change, run and end scheduled tasks on a local or remote
system. Replaces AT.exe.

Parameter List:
  /Create       Creates a new scheduled task.
  /Delete      Deletes the scheduled task(s).
  /Query        Displays all scheduled tasks.
  /Change        Changes the properties of scheduled task.
  /Run        Runs the scheduled task immediately.
  /End        Stops the currently running scheduled task.
  /?        Displays this help/usage.
  /S        parameter to specify a remote system for execution.

Examples:
  SCHTASKS
  SCHTASKS /?
  SCHTASKS /Run /?
  SCHTASKS /End /?
  SCHTASKS /Create /?
  SCHTASKS /Delete /?
  SCHTASKS /Query /?
  SCHTASKS /Change /?

SAMPLE Scheduled Task
=============================================
schtasks /create /tn “XPSP2” /tr “\\servershare\SP2fileshare\i386\update\update.exe /passive /forcerestart” /sc once
/st 20:00:00 /sd 04/08/2006 /ru “system”
====================================================
The above command all in one line saved as a batch file will schedule a task to install XPSP2 at 8pm, passively and restart the computer
when done. It will run under the context of system so no passwords are required.
It could be modified to do any number of things.
                                        Last Edited on July 22, 2006
                                                                                                                  Page 9
Backup Files using NTBackup




Backup1.bat
==================
@echo off
NTBACKUP backup daily.bks /m incremental /J dailybackup /D 20050501 /F \\SrvW2k01\Backup\SaveData.bkf
/HC:ON /L:S /V:yes /R:yes
==================

The above is all on line line and will backup to a network drive on the server SrvW2k01. It will backup the
systemstate using an incremental backup and continue appending to the file each time the backup is run.

Backup2.bat
   •   Create a .bks text file with folders to be backed up one per line
           – daily.bks
                     • D:\Pub\
                     • E:\users\
                     • SystemState
   •   Can schedule with NTBackup
           – with AT scheduler OR
           – With schtasks (new scheduler service)
   •   Can run from NTBackup OR command line
   •
   •   ======================================
   •   start /wait rsm.exe refresh /lf"Your_Library_Name"
   •   ntbackup.exe backup "daily.bks“ /v:no /r:no /rs:no /hc:on /m normal /j "daily.job" /l:f /p “4mm DDS" /um
   •   ======================================

   •   /lf – logical media friendly name
   •   /v – verify
   •   /r – restrict to owner or administrator group
   •   /rs – removable storage database
   •   /hc – hardware compression
   •   /m – type normal, incremental, …
   •   /j – job name
   •   /l – type of log file
   •   /p – media pool
   •   /um – magic bullet – will find 1st media of defined type, format, and use.




                                        Last Edited on July 22, 2006
                                                                                                                        Page 10

Schedule installation of XP sp2 at 8:00pm

=============================================
schtasks /create /tn “XPSP2” /tr “\\servershare\SP2fileshare\i386\update\update.exe /passive /forcerestart” /sc once /st 20:00:00 /sd
04/08/2006 /ru “system”
====================================================

The above command all in one line saved as a batch file will schedule a task to install XPSP2 at 8pm, passively and restart the computer
when done. It will run under the context of system so no passwords are required.
Obviously this framework could be modified to do any number of things.

=============================================
schtasks /create /s \\10.80.5.10 /tn “XPSP2” /tr “\\servershare\SP2fileshare\i386\update\update.exe /passive /forcerestart” /sc once /st
20:00:00 /sd 05/02/2005 /ru “system”
=============================================

Same as first example, except this version schedules the task on remote computer with IP# 10.80.5.10

-------------------------------------------------------------------------

Using “sdelete” SysInternal Utility to clean up Temp Files:
===================================
      sdelete -s -q “c:\Documents and Settings\%username%\Local Settings\Temp”
      sdelete -s -q “c:\Documents and Settings\%username%\Local Settings\Temporary Internet Files”
      ipconfig /flushdns
===================================

Paste the above lines into a batch file, and it will use sdelete (from sysinternals) to securely delete the temp files from IE and
firefox, and then flush the local resolver cache.
The caution is it will delete cookies and all, but that is fine for me. Someone that used or needed cookies might have a
problem with it, but it does help keep things cleaned up.
-------------------------------------------------------------------------

Collect SysInfo data on any set of machines on the network
1) Create a simple txt file that is a list of machines (netbios names or Ip‟s) that you would like to probe. Enter them one-per line
2) Execute a batch file that contains this line:
         psexec @list.txt systeminfo /fo CSV /nh >> \\fileshare\file.csv

        The /nh takes headers off of the output so it just appends the info to the bottom of the csv file.
        Start with a default csv file that is created by running the command on a single machine without the “/nh” switch so the header is
         generated..
        Then edit the default CSV file to contain only the header information. Just rename the file to what is appropriate each time before
         starting
        “list.txt” needs to be located in the same directory that you are executing from.
        The command executes under logged on users credentials.

psexec will also enumerate the domain and run it on each machine if you leave out the @list.txt part.
        Type psexec /? to see its syntax.




                                          Last Edited on July 22, 2006
                                                                                                                        Page 11
Delete local cached profiles on remote workstations.
1) Create a simple txt file that is a list of machines (netbios names or Ip‟s) that you would like to clean cached profiles on. Enter them one-
    per line
2) Execute a batch file that contains this line:
         PSEXEC.exe @delproflist.csv -high -c -f -d Delprof.exe /Q /D:30

         SAMPLE CURTISY of James C. August II, District Tech - Belvidere CUSD 100
         Mofifed with suggestion from Tech-Geek suggestion


        The delproflist.csv contains the list of computers to clean
        The –high switch specifies high priority
        The –c and –f switches copy the command to the remote system and force the copy respectively.
        The –d switch specifies not to delay or run interactively, but rather to execute immediately
        The /q switch is a parameter for the Delprof.exe utility

psexec will also enumerate the domain and run it on each machine if you leave out the @list.txt part.
        Type psexec /? to see its syntax.

SysInternals - http://www.sysinternals.com/




                                          Last Edited on July 22, 2006
                                                                                                     Page 12
VB Script – Cscript – Wscript
Windows Scripting Host (Wscript.exe)
    Object Language
    VBS code at first appears strange or busy. It seems to require a lot of commands to complete a minimal task
    Object Model
          o Based on tools or “objects” and actions or “methods”
                    Example
                          FileSystemObject
                                  o CopyFile
                                  o DeleteFile
                                  o FileExists
                                  o MoveFile
                                  o CopyFolder
                                  o DeleteFolder
                                  o FolderExists
                                  o MoveFolder
          o Uses dotted notation to connect and action to an object
                    object.method
    Best practice programming
          o Need to declare all variables (Dim variable)
          o Need to code variable types (object, integer, string, etc.)
          o Need to “instantiate” objects, basically declare and assign variable
                    Dim oFSO
                    Set oFSO = CreateObject("Scripting.FileSystemObject")
                    oFSO.CopyFile “source file” “destination”
          o Should initialize variables (Set variable = …)
          o Should release variable when done (Set variable = Nothing)
          o Should error trap
          o Should comment or document

Sample Script from TechRepublic, “Scripting Guide for Network Administrators”
'Script to copy MyFile.txt to network share
'===============================================================
' Instantiate FileSystemObject
'===============================================================
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
'===============================================================
' Test for existence of MyFile.txt and copy if exists
'===============================================================
If (objFSO.FileExists("C:\MyFolder\MyFile.txt ")) Then
     objFSO.CopyFile "C:\MyFolder\MyFile.txt", "\\Server1\SharedFolder\MyFile.txt"
Else
     WScript.Echo("Unable to locate file")
End if
'===============================================================
' Release FileSystemObject
'===============================================================
Set objFSO = Nothing
Wscript.Quit




                                   Last Edited on July 22, 2006
                                                                                       Page 13
LogonBanner00.vbs - Display logon message noting agreement to policies
===================================================
' ------------------------------------
' Simple message box for logon script
' Displays AUP/Policy agreement message
' ------------------------------------

Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Popup "By Logging into the Shiloh Network"&vbCRLF& _
"        you are agreeing"&vbCRLF& _
" to the AUP and District Policies"&vbCRLF&vbCRLF& _
"Network for Educational Use Only",0

WScript.Quit()

LogonBanner01.vbs - POPUP Logon message with option to display AUP
===================================================
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")

intMessage = Msgbox("By Logging onto the School Network"&vbCRLF&_
"    you have agreed to the AUP"&vbCRLF&_
"       and all District Policies"&vbCRLF&vbCRLF&_
"       Click YES to see the AUP?", vbYesNo, "Access Denied")

If intMessage = vbYes Then
   WshShell.Run("http://www.shiloh.k12.il.us/board/Policies/ShilohAUP2005-2006.htm")
Else
   Wscript.Quit
End If

WScript.Quit()


AddPrinter0.vbs - add mapped network printers
=======================================================
Dim WshNetwork

Set WshNetwork = CreateObject("WScript.Network")

On Error Resume Next
WshNetwork.RemovePrinterConnection "\\SrvW2k3app\HPLaserJ4100N", True, True
WshNetwork.RemovePrinterConnection "\\SrvW2k3app\HPLaserJ4050N", True, True
WshNetwork.RemovePrinterConnection "\\SrvW2k3app\HPColorLJ4600N", True, True
On Error GoTo 0

On Error Resume Next
 WshNetwork.AddWindowsPrinterConnection "\\SrvW2k3app\HPLaserJ4100N"
 WshNetwork.AddWindowsPrinterConnection "\\SrvW2k3app\HPLaserJ4050N"
 WshNetwork.AddWindowsPrinterConnection "\\SrvW2k3app\HPColorLJ4600N"
 WshNetwork.SetDefaultPrinter "\\SrvW2k3app\HPLaserJ4100N"
On Error GoTo 0
=======================================================




                                      Last Edited on July 22, 2006
                                                                                                                 Page 14
AddPrinter1.vbs – “includes code to remove all previously mapped printers”
===================================================
Dim WshNetwork, WshPrinter, intDrive, intNetLetter
Set WshNetwork = CreateObject("WScript.Network")

„this line reads (enumerates) all mapped printers into an array
Set WshPrinter = objNetwork.EnumPrinterConnections

' Extra section to troubleshoot
If WshPrinter.Count = 0 Then
 WScript.Echo "Warning: No Printers Mapped "
 Wscript.Quit(0)
End If

„This is the loop to cyle through and remove all mapped printers
For intDrive = 0 to WshPrinter.Count -1 Step 2
 WshNetwork.RemovePrinterConnection WshPrinter.Item(intDrive +1)
Next

On Error Resume Next
 WshNetwork.AddWindowsPrinterConnection "\\SrvW2k3app\HPLaserJ4050N"
 WshNetwork.AddWindowsPrinterConnection "\\SrvW2k3app\HPLaserJ4100N "
 WshNetwork.SetDefaultPrinter "\\SrvW2k3app\HPLaserJ4100N "
On Error GoTo 0

Wscript.Quit(1)

===================================================
EnumPrinterConnections.vbs
===================================================
' -----------------------------------------------------------'
' VBScript to Enumerate Printers.
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.8 - April 24th 2005
' -----------------------------------------------------------'

Option Explicit
Dim objNetwork, objPrinter, intDrive, intNetLetter

' Here is where objPrinter enumerates the mapped drives
Set objNetwork = CreateObject("WScript.Network")
Set objPrinter = objNetwork.EnumPrinterConnections

' Extra section to troubleshoot
If objPrinter.Count = 0 Then
 WScript.Echo "Warning: No Printers Mapped "
 Wscript.Quit(0)
End If

' Here is the where the script reads the array
For intDrive = 0 to objPrinter.Count -1 Step 2
 intNetLetter = IntNetLetter +1
 WScript.Echo "UNC Path " & objPrinter.Item(intDrive) & " = " & objPrinter.Item(intDrive +1) & " Printer : " & intDrive
Next

Wscript.Quit(1)
=======================================================



                                          Last Edited on July 22, 2006
                                                                              Page 15
MapDrive.vbs
=======================================================
Dim WshNetwork

Set objSh = WScript.CreateObject("WScript.Shell")
' objsh.Run "NET USE * /DELETE /YES", 0, True
' line above will remove all mapped drives if uncommented

Set WshNetwork = CreateObject("WScript.Network")

' next 2 lines below will remove specific network drives if uncommented
' WshNetwork.RemoveNetworkDrive "p:"
' WshNetwork.RemoveNetworkDrive "q:"

On Error Resume Next
 WshNetwork.MapNetworkDrive "p:" , "\\SrvW2k3app\pub"
 WshNetwork.MapNetworkDrive "q:" , "\\SrvW2k3app\data"
On Error GoTo 0

Wscript.Quit(0)

=======================================================

MapDrvPrtByOU.vbs - map network drive & printer based on OU of account
'***********************************************************************************
' Script Name: MapDrvPrtByOU.vbs
'     From TekTips Site - http://www.tek-tips.com/viewthread.cfm?qid=751336
'    Purpose: Map drives and printers by workstation OU.
'***********************************************************************************

On Error Resume Next

Set objNetwork = CreateObject("WScript.Network")
Set objAdsSystemInfo = CreateObject("adsysteminfo")
Set objComputerName = Getobject("LDAP://" & objAdsSystemInfo.ComputerName)
Set objOU = GetObject(objComputerName.Parent)
strOU = replace(objOU.Name,"CN=","")

'Map common drives
objNetwork.MapNetworkDrive "X:", "\\FileServer\users",True
objNetwork.MapNetworkDrive "Y:", "\\AppServer\executables",True

'Check OU membership and map drives/printers accordingly
For Each objOU In objUserName.Parent
 Select Case strOU
  Case "Engineering"
   objNetwork.MapNetworkDrive "W:", "\\FileServer\drawings\working",True
   objNetwork.AddWindowsPrinterConnection "\\PrintServer\Canon_iR5020i"
  Case "Accounting"
   objNetwork.MapNetworkDrive "M:", "\\AppServer\mas90",True
   objNetwork.AddWindowsPrinterConnection "\\PrintServer\Xerox470"
 End Select
Next

   set objOU = Nothing
   set objUserName = Nothing
   set objAdsSystemInfo = Nothing
   set objNetwork = Nothing
WScript.quit
=======================================================

                                       Last Edited on July 22, 2006
                                                                              Page 16
CopyFiles1a.vbs
=======================================================
Dim oFSO

'     Dim bOverwriteDestination
'     bOverwriteDestination = True

Set oFSO = CreateObject("Scripting.FileSystemObject")

' Copy all TXT files from server-folder \\SrvW2k3app\pub\ to local c:\test folder
oFSO.Copyfile "\\SrvW2k3app\pub\*.txt", "c:\test", True

Wscript.Quit
=======================================================

CopyFolder1a.vbs
=======================================================
Dim oFSO

    Dim bOverwriteDestination
    bOverwriteDestination = True

Set oFSO = CreateObject("Scripting.FileSystemObject")

'   Copy Folder from C:\Copy to SrvW2k3app\pub
oFSO.CopyFolder "c:\Copy", "\\SrvW2k3app\pub", True

Wscript.Quit
=======================================================

CopyFilebyDate.vbs
'***********************************************************************************
' Script Name: CopyFilebyDate.vbs
' Author: Brent Tuggle
' Version: 1.0   Last Updated: 05/03/2006
' Purpose: Copy a logfile from computer A to Computer B.
‘   The filename is "Today'sDate.log" .
'    Legal: Public Domain. Modify and redistribute freely. No rights reserved.
'    Script provided "as is" without implied warranty or guarantee. Use
'       at your own risk and only on networks with prior written permission.
'***********************************************************************************

Dim oFSO
           Dim sSourceFile
           Dim sDestinationFile

           Set oFSO = CreateObject("Scripting.FileSystemObject")

           sSourceFile = "\\remotecomputer.com\path\" & Today & ".log"
           sDestinationFile = "c:\localpath\"

           oFSO.Copyfile sSourceFile, sDestinationFile

           ' Clean Up
           Set oFSO = Nothing

           Main = DTSTaskExecResult_Success

'***********************************************************************************
' Function Name: Today
                                Last Edited on July 22, 2006
                                                                                        Page 17
'        Purpose: Return the Today's date in given format
'        Returns: Todays date at YYMMDD
'***********************************************************************************
  Function Today()
    Dim y, m, d
    y = Right(Year(Now), 2)
    m = Month(Now)
    If m < 10 Then m = "0" & CStr(m)
    d = Day(Now)
    If d < 10 Then d = "0" & CStr(d)
    Today = y & m & d
End Function

'END OF SCRIPT


BldShortCut.vbs – script will build a shortcut to WordPad and place it on the desktop
=======================================================
Dim aShortCut, strDesktop
Set WShell = Wscript.CreateObject("Wscript.Shell")
strDesktop = WShell.SpecialFolders("Desktop")

Set aShortcut = WShell.CreateShortcut(strDesktop & "\MyWordpad.lnk")

aShortcut.TargetPath = "C:\Program Files\Windows NT\Accessories\wordpad.exe"
aShortCut.WorkingDirectory = "c:\test"

aShortcut.Save

Wscript.Quit()
=======================================================

RunApps.vbs
„ Sample runs Notepad and Calculator –Twice, 2nd time with delays
=======================================================
'************************************************
' File: RunApps.vbs (WSH sample in VBScript) Author: (c) G. Born
' Launching Calculator and Notepad using the Run method
'************************************************
Option Explicit

Dim oShell

' Create the WshShell object.
Set oShell = WScript.CreateObject("WScript.Shell")

oShell.Run "Calc.exe", 1    ' Launch Calculator.
oShell.Run "NotePad.exe", 1 ' Launch Notepad.

WScript.Sleep 200       ' Wait 0.2 seconds

' Now add delay script after launching an application.
WScript.Echo "Second Attempt: Launch Notepad and Calculator"

oShell.Run "Calc.exe", 1 ' Launch Calculator.
WScript.Sleep 2000        ' Wait 2.0 seconds.
oShell.Run "NotePad.exe", 1 ' Launch Notepad.
WScript.Sleep 2000        ' Wait 2.0 seconds.

WScript.Echo "Please close all application windows"
Wscript.Quit()
                                       Last Edited on July 22, 2006
                                                                                                                  Page 18
DEFRAG Script -'This script launches defrag and sends keys to the User Interface (UI) in order to automate the defrag process.
=======================================================
set WshShell = CreateObject("WScript.Shell")

' Launch Defrag from the command line and wait for a second
WshShell.Run "dfrg.msc"
WScript.Sleep 1000

' Wait until the application has loaded - Check every second
While WshShell.AppActivate("Disk Defragmenter") = FALSE
  Wscript.Sleep 1000
Wend

' Bring the application to the foreground
WshShell.AppActivate "Disk Defragmenter"
WScript.Sleep 200

' Send an ALT-A key to bring down the defrag menu
WshShell.SendKeys "%A"
WScript.Sleep 200

' Send a D to start the defrag
WshShell.SendKeys "D"

' Wait until the defrag is completed - Check for window every 5 seconds
While WshShell.AppActivate("Defragmentation Complete") = FALSE
   wscript.sleep 5000
Wend

' Bring the msgbox to the foreground
WshShell.AppActivate "Defragmentation Complete"
WScript.Sleep 200

' Send a tab key to move the focus from View Report button to the Close Button
WshShell.Sendkeys "{TAB}"
Wscript.Sleep 500

' Send key to Close the Defragmentation Complete window
WshShell.Sendkeys "{ENTER}"
Wscript.Sleep 500

' Send and ALT-F4 to Close the Defrag program
WshShell.Sendkeys "%{F4}"
=======================================================

NumLock.vbs - toggle numlock on/off
=======================================================
'****************************************************
' Author: (c) G. Born
'****************************************************
Option Explicit
Dim WSH

' Create the WshShell object, required for SendKeys
Set WSH = WScript.CreateObject("WScript.Shell")

WSH.SendKeys "{NUMLOCK}" ' Toggle Num Lock.

WScript.Echo "Num Lock toggled"

WScript.Quit()    ' Terminate script.
                                        Last Edited on July 22, 2006
                                                                                                            Page 19
UserInfo.vbs
=======================================================
' Display the user name, domain name, and workgroup name

Option Explicit

Dim Text, Title
Dim WshNetwork         ' Object variable

Text = "Networking information" & vbCrLf & vbCrLf
Title = "WSH sample - by G. Born"

' Create a new WshNetwork object to access network properties.
Set WshNetwork = WScript.CreateObject("WScript.Network")

Text = Text & "Computer name : " & WshNetwork.ComputerName & vbCrLf
Text = Text & "Domain : " & WshNetwork.UserDomain & vbCrLf
Text = Text & "User name : " & WshNetwork.UserName & vbCrLf

MsgBox Text, vbOKOnly + vbInformation, Title

Wscript.Quit
=======================================================
SetLocalAdminPassword.vbs – will reset local admin password
=======================================================
strComputer = "."

Set objUser = GetObject("WinNT://" & strComputer & "/Administrator")

objUser.SetPassword "bhs2006#"
objUser.SetInfo

Wscript.Quit
=======================================================

LocalGroup.vbs – will add a local group called LocalAdmin to the Administrator group on the Local Machine
=======================================================
'-------------------------------------------------------------------------
' Script creates one local group called LocalAdmin
' Version 1.0, 8/27/03 Todd Woolums (twoolums@toddwoolums.com)
'-------------------------------------------------------------------------

' Set some string variables up
Domain = "shiloh.k12.il.us" 'Sets the string variable to the domain
strComputer = "." 'Sets target computer to local machine

' Sets the object to the local machine
' Creates the Local Group
' Adds to the local group
  Set groupQA = GetObject("WinNT://"& strComputer &"/Administrators")
  groupAdd.Add "WinNT://"& Domain &"/LocalAdmin"
  ' groupAdd.Add "WinNT://"& Domain &"/User2"    '--can be used to prepopulate users in group

MsgBox "Group has been added.", vbOKOnly + vbInformation

exit(0)



                                           Last Edited on July 22, 2006
                                                                                     Page 20
RenameWorkstation.vbs
=======================================================
'   -----------------------------
'    Brent Tuggle
'    Windows Administrator
'    Wolfram Research
'   -------------------------------

On Error Resume Next

' open the file system object
Set oFSO = CreateObject("Scripting.FileSystemObject")
set WSHShell = wscript.createObject("wscript.shell")

Dim sNewCname 'Variable to hold Computer Name you enter in the inputbox
Dim sOldCname 'computers current name

' First param is message text, second is message title
   sOldCname = InputBox("Enter computers current name","Windows 2k3 Netdom Rename Script")
   sNewCname = InputBox("Enter computers new name","Windows 2k3 Netdom Rename Script")

Call WSHShell.Run("cmd.exe /c NETDOM RENAMECOMPUTER " & sOldCname & " /newname:" & sNewCname
& " /userd:tsulliva /passwordd:* /Force /reboot:45")

exit

GetNics.vbs -- will read and display network card information
=======================================================
' --------------------------------------------
' GetNics.vbs
' Support Site: http://www.mousetrax.com
' Author: Greg Chapman
' Date: 5/24/2002
' ---------------------------------------------
' Force Declaration of Variables
Option Explicit

'Declare Variables
Dim j, NIC1, Nic, StrNic, lngCount, StrIP, i ,objNet,objHost

'If something fails, move on
On Error Resume Next

'Get the Computer's network name
Set objNet=CreateObject("wscript.Network")
objHost=objNet.ComputerName
Wscript.Echo "Analysis of " & objHost & "."

'Get a connection to the WMI NetAdapteConfig object
Set NIC1 = GetObject("winmgmts:").InstancesOf("Win32_NetworkAdapterConfiguration")

'For Each of the NICs in the connection
For Each Nic in NIC1
  'Get the Adapter Description
  StrNIC = Nic.Description
   'If IP is enabled on the NIC then let's find out about the NIC
   IF Nic.IPEnabled THEN
      lngCount=UBound(Nic.IPAddress)
      For i=0 to lngCount
        If i >= 0 Then
                                             Last Edited on July 22, 2006
                                                                         Page 21
wscript.echo "===================================================" & _
    vbNewLine
wscript.echo StrNic & vbNewLine
StrIP = vbTab & Nic.IPAddress(i)
If StrIP <> "" Then
  WScript.Echo vbTab & "IP Address = " & _
     StrIP

 WScript.Echo vbTab & "MAC Address = " & _
  Nic.MACAddress

 Wscript.Echo vbTab & "NIC Service (Short) Name = " & _
 Nic.ServiceName

  WScript.Echo vbTab & "IP Subnet(s): "
  For j = 0 to UBound(Nic.IPSubnet)
    Wscript.Echo vbTab & vbTab & Nic.IPSubnet(j)
  Next
  Wscript.Echo vbTab & "Internet Database Files Path = " & _
     Nic.DatabasePath
  Wscript.Echo vbTab & "Dead Gateway Detection = " & _
     Nic.DeadGWDetectEnabled

  Wscript.Echo vbTab & "IP Gateway(s): "
  For j=0 to UBound(Nic.DefaultIPGateway)
     Wscript.Echo vbTab & vbTab & Nic.DefaultIPGateway(j)
  Next

  If Nic.DHCPEnabled Then
     Wscript.Echo vbTab & "DHCP Assigned IP address = " & _
       Nic.DHCPEnabled

    Wscript.Echo vbTab & "DHCP Server = " & _
      Nic.DHCPServer
    End If

    Wscript.Echo vbTab & "DNS for WINS Resolution Enabled = " & _
     Nic.DNSEnabledforWINSResolution

    Wscript.Echo vbTab & "DNS Host Name = " & _
     Nic.DNSHostName

    Wscript.Echo vbTab & "DNS Servers:"
    For j=0 to UBound(Nic.DNSServerSearchOrder)
      Wscript.Echo vbTab & vbTab & Nic.DNSServerSearchOrder(j)
    Next

    Wscript.Echo vbTab & "IP Port Filtering Enabled = " & _
     Nic.IPFilterSecurityEnabled

    If Nic.IPFilterSecurityEnabled Then
       WScript.Echo vbTab & "IP Filtering Enabled."
       If Nic.IPSecPermitIPProtocols <> 0 Then
         For j=0 to UBound(Nic.IPSecPermitIPProtocols)
             Wscript.Echo vbTab & vbTab & "Protocol: " & _
                Nic.IPSecPermitIPProtocols(j)
         Next
       Else
         Wscript.Echo vbTab & vbTab & "No Protocols Filtered"
       End If

       If Nic.IPSecPermitTCPPorts <> 0 Then
                               Last Edited on July 22, 2006
                                                                                                                        Page 22
                  For j=0 to UBound(Nic.IPSecPermitTCPPorts)
                      WScript.Echo vbTab & vbTab & "TCP Port: " & _
                         Nic.IPSecPermitTCPPorts(j)
                  Next
                 Else
                  Wscript.Echo vbTab & vbTab & "No TCP Ports Filtered"
                 End If

                If Nic.IPSecPermitUDPPorts <> 0 Then
                  For j=0 to UBound(Nic.IPSecPermitUDPPorts)
                      Wscript.Echo vbTab & vbTab & "UDP Port: " & _
                         Nic.IPSecPermitUDPPorts(j)
                  Next
                 Else
                  WScript.Echo vbTab & vbTab & "No UDP Ports Filtered"
                 End If
               End If

               Wscript.Echo vbTab & "LMHOSTS Lookup Enabled = " & _
                  Nic.WINSEnableLMHostsLookup

               Wscript.Echo vbTab & "WINS Lookup File = " & _
                  Nic.WINSHostLookupFile

               Wscript.Echo vbTab & "Primary WINS Server = " & _
                  Nic.WINSPrimaryServer

               Wscript.Echo vbTab & "Secondary WINS Server = " & _
                  Nic.WINSSecondaryServer

               Wscript.Echo vbTab & "WINS Scope ID = " & Nic.WINSScopeID

           End If
         End If
       Next
      END IF
    Next

Display_user_info.vbs
=======================================================
'~~Author~~. Ralph Montgomery
'~~Email_Address~~. rmonty@myself.com
'~~Script_Type~~. vbscript
'~~Sub_Type~~. DomainAdministration
'~~Keywords~~. User administration, usrmgr, ADSI, user password, ExpandEnvironmentStrings, Password History, vbscript
'~~Comment~~.
'Query for a domain name, user name and return all the properties of a user
'account in a popup box. Requires NO customizations, will run on Win95,
'WinNT, W2k, user requires NO rights to the data. Script checks For
'installation of Script Version and ADSI and prompts for installation.

'~~Script~~.
' Get User Information NTUser.wsf
' Revision history:
' 12/13/01 Changed from VBScript (.vbs) file to Window Scripting Host file type. (.wsf)
' 12/22/01 added Windows 9x error checking and routines to work under Win9x
' 01/01/02 added Password Expiration Date, Passwords Kept in History
'                         reordered the information popup box for readability

' Created 11-26-2001 by Ralph Montgomery - Firsthealth of the Carolinas (rmonty@myself.com)

' Initialize the variable farm
Dim objUserName, objUserDomain, objGroup, objUser, strGroupList, WshShell, strMessage, strTitle
Dim objDomain, strDomain, strUserName, strOS
                                         Last Edited on July 22, 2006
                                                                                      Page 23
Dim objChangePwdTrue, objChangePwd, objUserProfile
Dim objPwdExpiresTrue, objFlags, oPwdExpire, strPwdExpires
Dim objAcctDisabled, intPwdExpired, objPwdExpiredTrue

' Set WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")

' Pull Environment variables for domain/user
strDomain = WshShell.ExpandEnvironmentStrings("%USERDOMAIN%")
strUserName = WshShell.ExpandEnvironmentStrings("%USERNAME%")
strOS = WshShell.ExpandEnvironmentStrings("%OS%")

SysTest ' sub routine to check for Script Version/ADSI installed

GetInfo ' sub routine to get user information

on error resume Next
' Creates the list of goups the user belongs to
For Each objGroup In objUser.Groups
                              If strGroupList = "" Then
                                 strGroupList = objGroup.Name
                              Else
                                 strGroupList = strGroupList & ", " & objGroup.Name
                              End If
Next

'check for expired password
intPwdExpired = objUser.Get("PasswordExpired")

                             If intPwdExpired = 1 Then
                                 objPwdExpiredTrue = "Yes"
                                 Else objPwdExpiredTrue = "No"
                             End If

'Check for Must Change Password Flag
objFlags = objUser.Get("UserFlags")

                             If (objFlags And &H00040) <> 0 Then
                                 objChangePwdTrue = "No"
                                 Else objChangePwdTrue = "Yes"
                             End If

' Is password set to NEVER expire?
objPwdExpires = objUser.Get("UserFlags")

                             If (objPwdExpires And &H10000) <> 0 Then
                                 objPwdExpiresTrue = "Yes"
                                          strPwdExpires = "Password Set: "
                                 Else objPwdExpiresTrue = "No"
                                          strPwdExpires = "Password Expires: "
                             End If

' Is the account disabled?
                             If objUser.AccountDisabled = True Then
                                objAccountDisabled = "Yes"
                                Else objAccountDisabled = "No"
                             End If

'How many wrong logins?
Int(objBadLogins) = objUser.BadLoginCount

' How old is the current password?
oPwdAge = objUser.Get("PasswordAge")
objPwdAge = FormatNumber(((oPwdAge/60)/60)/24, 0)

' Set Profile path to tabs if blank
                                                Last Edited on July 22, 2006
                                                                                                                              Page 24
                           If objUserProfile = "" Then
                              objUserProfile= "<None>" & vbTab
                              Else objUserProfile = objUserProfile
                           End If

' Determine how many passwords are saved
Set Domain = GetObject("WinNT://" & objDomain)
Int(intPwdHistory) = Domain.PasswordHistoryLength

' Set strMessage box variables to null
strMessage =""

'popup user information: each line broken up for better reading
strMessage = strMessage & "Domain: " & objDomain & vbTab & "User Name: " & objUserName & vbTab & "Full Name: " & objUser.FullName &
vbCrLf
strMessage = strMessage & "Description: " & objUser.Description & vbCrLf & vbCrLf

strMessage = strMessage & "Account Locked Out: " & objUser.IsAccountLocked & vbTab & "Account Disabled: " & objAccountDisabled & vbCrLf
strMessage = strMessage & "Bad Logins: " & objBadLogins & vbTab & vbTab & "Last logon: " & objUser.LastLogin & vbCrLf & vbCrLf

'strMessage = strMessage & "Parameters: " & objUser.Parameters("CtxWFProfilePath") & vbCrLf & vbCrLf

strMessage = strMessage & "Password Expired: " & objPwdExpiredTrue & vbTab & "Password Age: " & objPwdAge & " days" & vbCrLf
strMessage = strMessage & "Password Never Expires: " & objPwdExpiresTrue & vbTab & strPwdExpires & objUser.PasswordExpirationDate & vbCrLf
& vbCrLf

strMessage = strMessage & "User can change Pwd: " & objChangePwdTrue & vbTab & "Password Minimum Length: " &
objUser.PasswordMinimumLength & vbCrLf
strMessage = strMessage & "Passwords Kept In History: " & vbTab & intPwdHistory & " password(s)" & vbCrLf & vbCrLf

strMessage = strMessage & "Login Script: " & objUser.LoginScript & vbTab & "Home Directory: " & objUser.HomeDirectory & vbCrLf
strMessage = strMessage & "User Profile Path: " & objUserProfile & vbCrLf & vbCrLf

strMessage = strMessage & "User Groups: " & vbCrLf & vbCrLf & strGroupList & vbCrLf

' Display User Information!
WshShell.Popup strMessage,0,"User Information for: " & objUserName & " in " & objDomain

Sub GetInfo()
                           ' Define user then retrieve and store groups in a list
                           ' Retrieve Domain from user
                           If strOS = "Windows_NT" Then

                           strMessage = "Please enter the domain to search." & vbCrLf & vbCrLf & _
                           "Default is: " & strDomain & vbCrLf & vbCrLf
                           strMessage = strMessage & "Hit Cancel or enter a blank to quit"
                           strTitle = "Domain to Search"

                              'get resource domain name, domain default
                              objDomain = InputBox(strMessage, strTitle, strDomain)

                             ' Evaluate the user input.
                             If objDomain = "" Then ' Cancelled by the user
                                WScript.quit
                             End If
                           Else        'must be Windows 9x

                           strMessage = "Please enter the domain to search." & vbCrLf & vbCrLf & "Hit Cancel or enter a blank to quit"
                           strTitle = "Domain to Search"

                              'get resource domain name, domain default
                              objDomain = InputBox(strMessage, strTitle)

                              ' Evaluate the user input.
                              If objDomain = "" Then ' Cancelled by the user
                                 WScript.quit
                              End If
                                              Last Edited on July 22, 2006
                                                                                                          Page 25
                End If
                ' Set strMessage box variables to null
                strMessage = ""
                strTitle = ""

                on error resume Next

                ' Define username dialog box variables.

                If strOS = "Windows_NT" Then
                strMessage = "Please enter the USER Login ID" & vbCrLf & vbCrLf & _
                "Default is: " & strUserName & vbCrLf & vbCrLf
                strMessage = strMessage & "Hit Cancel or enter a blank to quit"
                strTitle = "USER Login ID"

                  'get resource domain name, domain default via input box
                  objUserName = InputBox(strMessage, strTitle, strUserName)

                  ' Evaluate the user input.
                  If objDomain = "" Then ' Cancelled by the user
                     WScript.quit
                  End If

                Else        ' If NOT Windows NT then must be Win 9x

                strMessage = "Please enter the USER Login ID" & vbCrLf & vbCrLf
                strMessage = strMessage & "Hit Cancel or enter a blank to quit"
                strTitle = "USER Login ID"
                'get resource domain name, domain default via input box
                   objUserName = InputBox(strMessage, strTitle)

                  ' Evaluate the user input.
                  If objDomain = "" Then ' Cancelled by the user
                     WScript.quit
                  End If
                End If

                  ' Display Just a minute!
                  strMessage = "This may take a few seconds. . ."
                  WshShell.Popup strMessage,2,"One moment please. . . "
                  strMessage = ""

                'Attempt to bind to the user
                Set objUser = GetObject("WinNT://"& objDomain &"/"& objUserName & "",user)


                If Err <> 0 Then
                For Each User In objUser
                             If Left(User.Name, 3) = Left(objUserName, 3) Then
                                       uList = User.Name & " " & User.Fullname
                             End If
                   Next
                   msgNoUser = "Error: Could not find: " & vbCrLf _
                             & vbCrLf & "WinNT://" & objDomain &"/"& objUserName & vbCrLf & vbCrLf _
                             & "Perhaps you meant one of these others?" & vbCrLf & vbCrLf
                   msgNoUser = MsgNoUser & uList

                  WshShell.Popup msgNoUser,0,"Error retrieving information",vbCritical
                  GetInfo
                Else
                  msgConnected = "Connected to user WinNT://" & objDomain &"/"& objUserName & vbCrLf
                  WshShell.Popup msgConnected,0,"Connected To " & objUserName & " in " & objDomain, vbInformation

                End If
End Sub

Sub SysTest()
                                  Last Edited on July 22, 2006
                                                                                                                        Page 26
                      on error resume Next
                      ' Replace \\servername\folder with you own locations. Only customization necessary!

                      ' WSH version tested
                      Major = (ScriptEngineMinorVersion())
                      Minor = (ScriptEngineMinorVersion())/10
                      Ver = major + minor
                      'Need version 5.5

                      If err.number or ver = 5.6 then
                         strMessage = "You must load Version 5.5 (or later) of Windows Script Host" & vbCrLf &_
                         vbCrLf & "Located at: \\servername\folder\scr56en.exe" & vbCrLf
                         strMessage = strMessage & "Consult the documentation at \\servername\folder\NTUser.doc for details"
                         WScript.Quit
                      End If

                      'Test for ADSI
                      err.clear
          key = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Active Setup\Installed Components\{E92B03AB-B707-11d2-9CBD-0000F87A369E}\version"
                      key2 = WshShell.RegRead (key)
                      If Err <> 0 Then
                      If strOS = "Windows_NT" Then
                         strMessage = "ADSI 5.2 must be installed on local workstation to continue" & vbCrLf &_
                         vbCrLf & "Located at: \\servername\folder\adsi5.2.exe" & vbCrLf
                         strMessage = strMessage & "Consult the documentation at \\servername\folder\NTUser.doc for details"
                         WshShell.Popup strMessage,0,"Workstation Setup Error",vbCritical
                         WScript.Quit
                      Else ' Must be Windows 9x
                         strMessage = "You appear to be running Windows 9x. If this is true, then" & vbCrLf
                         strMessage = strMessage & "ADSI 5.2 AND WMI must be installed on local workstation to continue" & vbCrLf &_
                         vbCrLf & "Located at: \\servername\folder\adsi5.2.exe and dsclient.exe" & vbCrLf
                         strMessage = strMessage & "Consult the documentation at \\servername\folder\NTUser.doc for details"
                         WshShell.Popup strMessage,0,"Workstation Setup Error",vbCritical
                         WScript.Quit
                      End If
                      End If
End Sub
=======================================================




                                       Last Edited on July 22, 2006
                                                                        Page 27
ListDrives.vbs
=======================================================
'**************************************************
' Author: (c) G. Born
' Listing the drives of a machine by using FileSystemObject
'**************************************************
Option Explicit

' Drive type constants
Const Unknown = 0
Const Removable = 1 ' Removable medium
Const Fixed = 2     ' Fixed medium (hard disk)
Const Remote = 3 ' Network drive
Const CDROM = 4         ' CD-ROM
Const RAMDisk = 5 ' RAM disk

Dim Text, Title
Dim fso, oDrive, curDrive   ' Object variables

Dim drtype(6)
drtype(0) = " Unknown "
drtype(1) = " Removable "
drtype(2) = " Fixed "
drtype(3) = " Remote "
drtype(4) = " CDROM "
drtype(5) = " RAMDisk "

Text = "Drives" & vbCrLf & vbCrLf
Title = "WSH sample - by G. Born"

' Create FileSystemObject object to access the file system.
Set fso = WScript.CreateObject("Scripting.FileSystemObject")

Set oDrive = fso.Drives   ' Get Drives collection.

For Each curDrive In oDrive     ' All drive objects
  Text = Text & curDrive.DriveLetter & vbTab ' Drive letter
  Text = Text & drtype(curDrive.DriveType)
  Select Case curDrive.DriveType       ' Identify drive type.
     Case Removable            ' Removable medium
       If curDrive.IsReady Then
          Text = Text & curDrive.VolumeName ' Local drive
       End If

    Case CDROM                 ' CD-ROM
      If curDrive.IsReady Then
         Text = Text & curDrive.VolumeName ' Local drive
      End If

    Case Remote
      Text = Text & curDrive.ShareName ' Network drive

     Case Else             ' Other medium
       Text = Text & curDrive.VolumeName ' Local drive
  End Select
  Text = Text & vbCrLf
Next

MsgBox Text, vbOKOnly + vbInformation, Title
'*** End
                                         Last Edited on July 22, 2006
                                                                                                                 Page 28
GetDriveX.vbs
' ************************************************
' Author: (c) G. Born
' Showing the properties of a drive by using FileSystemObject
' ************************************************
Option Explicit

' Drive type constants
Const Unknown = 0
Const Removable = 1 ' Removable medium
Const Fixed = 2         ' Fixed medium (hard disk)
Const Remote = 3       ' Network drive
Const CDROM = 4        ' CD-ROM
Const RAMDisk = 5 ' RAM disk

Dim Text, Title, drive
Dim fso, oDrive           ' Object variable
Dim drtype(6)
drtype(0) = " Unknown "
drtype(1) = " Removable "
drtype(2) = " Fixed "
drtype(3) = " Remote "
drtype(4) = " CDROM "
drtype(5) = " RAMDisk "

Text = "Drive" & vbCrLf & vbCrLf
Title = "WSH sample - by G. Born"

drive = ""
Do               ' Query drive letter.
   drive = InputBox("Drive letter (e.g. A)", "Drive", "C")

  If drive = "" Then ' Test for Cancel button.
     WScript.Quit
  End If

  drive = Left(drive, 1) ' Extract drive letter.

  ' Valid drive name (between A and Z)?
  If Asc(UCase(drive)) < Asc("A") Or Asc(UCase(drive)) > Asc("Z") Then MsgBox "Drive " & drive & " is illegal"
     drive = ""
  End If
Loop Until drive <> ""

' Create FileSystemObject object to access the file system.
Set fso = WScript.CreateObject("Scripting.FileSystemObject")

' Check whether drive exists.
If (Not fso.DriveExists(drive)) Then WScript.Echo "The drive " & drive & " doesn't exist"
   WScript.Quit
End If

Set oDrive = fso.GetDrive(drive)     ' Get Drive object.

If (oDrive.IsReady) Then
   Text = Text & UCase(drive) & " - " & oDrive.VolumeName & vbCrLf
   Text = Text & "Drive type: " & drtype(oDrive.DriveType) & vbCrLf
   Text = Text & "File system: " & oDrive.FileSystem & vbCrLf
   Text = Text + "Capacity: " & FormatNumber(oDrive.TotalSize/(1024*1024), 0) & " MB" & vbCrLf
   Text = Text & "Free: " & FormatNumber(oDrive.FreeSpace/1024, 0) & " KB" & vbCrLf
Else
   Text = Text & "Drive not ready" & vbCrLf
End If

MsgBox Text, vbOKOnly + vbInformation, Title
'*** End

                                                   Last Edited on July 22, 2006
                                                                              Page 29
MapDriveByGroup.vbs
=======================================================
'   MapDriveByGroup.vbs
'   Brent Tuggle
'   Windows Administrator
'   Wolfram Research

'Script to map a network drive based on Domain Group Membership

'Map N: Drive to temp-store
'Change the group name in "IsMemberOf" to reflect 'the group you want to map to.
'Set the drive letter in the "MapDdrive" line and set the 'UNC path here also

If IsMemberOf("AD Group Here") Then
                MapDrive "N:","\\UNC\File_path\here"
                End If

'-----------------------------------
'Sub Section
'-----------------------------------


'Subroutine to Map a drive using a UNC path Sub MapDrive(sLetter, sUNC)
                Set oNet = WScript.CreateObject("WScript.Network")
                oNet.MapNetworkDrive sLetter, sUNC
End Sub

'------------------------------------
'Functions Section
'------------------------------------

'Function to Determine Group Membership
Function IsMemberOf(sGroupName)
                Set oNetwork = CreateObject("WScript.Network")
                sDomain = oNetwork.UserDomain
                sUser = oNetwork.UserName
                bIsMember = False
                Set oUser = GetObject("WinNT://" & sDomain & "/" & _
                  sUser & ",user")
                For Each oGroup In oUser.Groups
                  If oGroup.Name = sGroupName Then
                        bisMember = True
                        Exit For
End If
Next
                IsMemberOf = bIsMember
End Function




                            Last Edited on July 22, 2006
                                                                                         Page 30
BulkAddUser.vbs
=======================================================
'     ---------------------
'     SteeleBulkAddUser.vbs
'     Tom Steele
'     Technology Director
'     Manteno 5
'     ---------------------

'// Name: bulkadduser1.vbs
'// Purpose: Create user script from CSV file

'//    Notes:
'//    1. Input file must be comma delimited
'//    2. Fields must be in the following order and must not be left blank:
'//       First Name, Last Name, Password, Group Name, Child OU 1, Child OU2, Child OU 3,
'//       SAM Logon, Home Drive, Logon Script, Description, Home Directory
'//    3. Must run stupermissions.bat AFTER this script to set permissions on home folders
'//    4. Must be member of Domain Admins group to run
'//    5. OU's and groups must have been created prior to running this script
'//    6. Home Directory must use full USN path, i.e. \\SERVER\SHARE\username -- system
'//      variables are not allowed
'//    7. Must change InpFile and batFile to correct drive and path prior to running script

'// Define variables

Option Explicit
Dim oFSO, oTF, oOU, oUser, oGroup, oRoot, oFolder, oPerm, oShell, oExec Dim sCN, sOU1, sOU2,
sOU3 Dim aLine, sLine, sLogon, sPass, sGroup, sRoot, sDN, vFlg Dim sFname, sLName,
sHomedrive, sLogscript, sDescription, sHomeDir


'// Set file names -- replace these with desired files

Const InpFile = "T:\stuimport.csv"                  'Import file
Const batFile = "T:\stupermissions.bat"             'batch file used for resetting home dir permissions

Const ForReading = 1
Const ForWriting = 2
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oTF = oFSO.OpenTextFile(InpFile,ForReading,True)
Set oPerm = oFSO.OpenTextFile(batFile,ForWriting,True)
Set oShell = CreateObject("WScript.Shell")


'// vFlg verifies that required fields are in input file
vFlg = True

Do While oTF.AtEndOfStream <> True
sLine = oTF.ReadLine
aLine = split(sline, ",",-1,1)
sFname = aLine(0)
sLname = aLine(1)
'// Sets container name to Last Name, First Name
sCN = sLname &"\, "&sFname
sPass = aLine(2)
sGroup = aLine(3)
sOU1 = aLine(4)
sOU2 = aLine(5)
sOU3 = aLine(6)
sLogon = aLine(7)
                              Last Edited on July 22, 2006
                                                                              Page 31
sHomedrive = aLine(8)
sLogscript = aLine(9)
sDescription = aLine(10)
sHomeDir = aLine(11)

'// WScript.Echo "Top of user loop" & sCN


If vFlg = True Then
 If isEmpty(sGroup) Or isEmpty(sOU3) Or isEmpty(sOU2) Or isEmpty(sOU1)
Then
  msgbox "Missing Parameter" & vbCr & _
  "First Line must contain:" & vbCr & _
  "First Name, Last Name, Password, Group Name, Child OU, Child OU, Root OU," & vbCr & _
  "SAM Logon ID, Home Drive, Logon Script, Description, Home Directory",_
  vbExclamation, "Add Bulk Users"
  wscript.Quit
 Else
  vFlg = False
 End If
End If

'// Call the Create User routine
CreateaUser

'// Call the add to Group routine
Add2Group(sDN)

'// WScript.Echo "End of user loop"

Loop

oPerm.Close


Msgbox "Script complete." & vbCr & _
"Run stupermissions.bat to set proper permissions on Home folders" _
,vbInformation, "Add Bulk Users"

Set    oTF = Nothing
Set    oFSO = Nothing
Set    oUser = Nothing
Set    oGroup = Nothing
Set    oOU = Nothing
Set    oRoot = Nothing

'//--------------------------
'// Create User subroutine
'//--------------------------

Sub CreateaUser()

'// Bind to the domain Root
Set oRoot = GetObject("LDAP://rootDSE")
sRoot = oRoot.Get("defaultNamingContext")

'// Bind to the OU where users are to be added
Set oOU = GetObject("LDAP://ou=" & sOU1 & ",ou=" & sOU2 & ",ou=" & sOU3 & "," & sRoot)

'// Remove comment from following line to enable screen display for debug
'// msgbox sCN & "ou=" & sOU1 & ",ou=" & sOU2 & ",ou=" & sOU3 & "," & sRoot
                           Last Edited on July 22, 2006
                                                                              Page 32
Set oUser = oOU.Create("user", "cn=" & sCN)

'// Remove comment from following line to enable error check from Create operation for debug
'// If err.number<>0 then msgbox err.number

On Error Resume Next

'// Load fields in AD record
oUser.put "sAMAccountName", lcase(sLogon)
oUser.put "givenName", sFname
oUser.put "sn", sLname
oUser.put "UserPrincipalName", lcase(sLogon)&"@manteno.local"
oUser.put "DisplayName", sLname &", "&sFname
oUser.put "name", sCN
oUser.put "homeDrive", sHomedrive
oUser.put "scriptPath", sLogscript
oUser.put "description", sDescription
oUser.put "homeDirectory", sHomeDir
oUser.SetInfo

'// Test for duplicate User
If err.number = -2147019886 then
 msgbox "User logon for " & sLogon & " already exists." _
 ,vbExclamation, "Add Bulk Users"
 Exit Sub
End If

'// Set initial password
oUser.setpassword sPass

oUser.AccountDisabled = False
oUser.SetInfo

'// Create user home folder
Set oFolder = oFSO.CreateFolder(sHomeDir)

'// Write line to bat file for cacls command to reset ACL on user home dir
oPerm.WriteLine("echo y|cacls "& sHomeDir &" /G "& lcase(sLogon) &":F Administrators:F
StudAcc:F")

'// Set the User's DN for adding to group
sDN = oUser.get("DistinguishedName")
End Sub


'//--------------------------
'// Add to Group subroutine
'//--------------------------

Sub Add2Group(Byval sDN)

Const ADS_PROPERTY_APPEND = 3

On Error Resume Next

'// msgbox "sGroup = "& sGroup & ",ou1=" & sOU1 & ",ou2=" & sOU2 & ",ou3=" & sOU3 &
",sRoot=" & sRoot _
'// ,vbExclamation, "Add Bulk Users"

'// Test if group is empty
                             Last Edited on July 22, 2006
                                                                              Page 33
If IsEmpty(oGroup) Then
  'Set oGroup = GetObject _
  ' ("LDAP://cn=" & sGroup & ",ou=" & sOU1 & ",ou=" & sOU2 & ",ou=" & sOU3 & "," & sRoot)
Set oGroup = GetObject("LDAP://cn=" & sGroup & ",ou=" & sOU1 & ",ou=" & sOU2 & ",ou=" & sOU3
& "," & sRoot)
End If

'// Add user to group
oGroup.PutEx ADS_PROPERTY_APPEND, _
 "member", Array(sDN)
oGroup.SetInfo
sDN = Nothing

'// Test if user is already member of group
If err.number <> 0 Then
 msgbox "User " & sLogon & _
 " is already a member of " & sGroup, _
 ,vbExclamation, "Add Bulk Users"
 Exit Sub
End If

End Sub




                           Last Edited on July 22, 2006
                                                                                                                 Page 34
PrimaryStudent.vbs
=======================================================
' PrimaryStudent login script
' Created by Tom Steele for Manteno School District
' For use in Primary School only

Option Explicit

Dim strComputer,objWMIService,IPConfigSet,IPConfig,aIP,sIP,i
Dim colOperatingSystems, objOperatingSystem

const shutdownmode = 0                                     '// 0 = Logoff
                                                                            '// 1 = Shutdown
                                                                            '// 2 = Reboot
                                                                            '// 4 = Forced Logoff (no notification to apps)
                                                                            '// 5 = Forced Shutdown
                                                                            '// 6 = Forced Reboot
                                                                            '// 8 = Power off
                                                                            '// 12 = Forced power off

Const soct1 = 10         'Hard coded first octet of building IP
Const soct2 = 20         'Hard coded second octet of building IP
Const soct3 = 0                  'Hard coded third octet of building IP

'// Call getIP routine
getip
if sIP(0)<>soct1 or sIP(1)<>soct2 then
          Set colOperatingSystems = GetObject("winmgmts:{(Shutdown)}").ExecQuery("Select * from Win32_OperatingSystem")
          For Each objOperatingSystem in colOperatingSystems
                    ObjOperatingSystem.Win32Shutdown(shutdownmode)
          Next
End If

'// Call

Sub getIP()
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set IPConfigSet = objWMIService.ExecQuery _
("Select IPAddress from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE")
For Each IPConfig in IPConfigSet
If Not IsNull(IPConfig.IPAddress) Then
For i=LBound(IPConfig.IPAddress) to UBound(IPConfig.IPAddress)
aIP=split(IPConfig.IPaddress(i),".",-1,1)
if aIP(0)=10 Then sIP=aIP
'WScript.Echo IPConfig.IPAddress(i)
Next
End If
Next
'WScript.Echo "AIP(0) " & aIP(0)
'Wscript.Echo "sIP(0)" & sIP(0)
'Wscript.Echo "sIP(1)" & sIP(1)
End Sub




                                       Last Edited on July 22, 2006
                                                                                 Page 35
Shutdown1.vbs
=======================================================
Sub ShutDown()
 Dim Connection, WQL, SystemClass, System

 'Get connection To local wmi
 Set Connection = GetObject("winmgmts:root\cimv2")

 'Get Win32_OperatingSystem objects - only one object In the collection
 WQL = "Select Name From Win32_OperatingSystem"
 Set SystemClass = Connection.ExecQuery(WQL)

 'Get one system object
 'I think there is no way To get the object using URL?
 For Each System In SystemClass
   System.Win32ShutDown (2)
 Next
End Sub

'Value Meaning
'0 Log Off
'0 + 4 Forced Log Off
'1 Shutdown
'1 + 4 Forced Shutdown
'2 Reboot
'2 + 4 Forced Reboot
'8 Power Off
'8 + 4 Forced Power Off

' Simple extension to shutdown remote computer.
'Sub ShutDownEx(Server, User, Password)
' Dim Connection, WQL, SystemClass, System
'
' 'Get connection To remote wmi
' Dim Locator
' Set Locator = CreateObject("WbemScripting.SWbemLocator")
' Set Connection = Locator.ConnectServer(Server, "root\cimv2", User, Password)
'
' 'Get Win32_OperatingSystem objects - only one object In the collection
' WQL = "Select Name From Win32_OperatingSystem"
' Set SystemClass = Connection.ExecQuery(WQL)
'
' 'Get one system object
' 'I think there is no way To get the object using URL?
' For Each System In SystemClass
' System.Win32ShutDown (2)
' Next
'End Sub
=======================================================




                                        Last Edited on July 22, 2006
                                                                                                 Page 36
PurgFiles.vbs - deletes all files in a tree which have not been modified since specified date.
=======================================================
' ***********************************************
'   Based on original script by Matt Harris
'   downloaded from http://www.codecomments.com/archive299-2004-12-343779.html
'   copied from web on 2006-07-05
' ***********************************************

' folder to start search in (will not be included)...
sRootPath = "C:\data"

' delete files older than 7 days...
killdate = date() -700

arFiles = array()
set fso = createobject("scripting.filesystemobject")

'   Don't do the delete while you still are looping through a
'   file collection returned from the File System Object (FSO).
'   The collection may get mixed up.
'   Create an array of the file objects to avoid this.

SelectFiles sRootPath, killdate, arFiles

nDeleted = 0
for n = 0 to ubound(arFiles)
'=================================================
' Files deleted via FSO methods do *NOT* go to the recycle bin!!!
'=================================================
on error resume next 'in case of 'in use' files...

' (*) do your backup task here here

' (*) just for test/demo purpose, remove this line when satisfied
‘ WScript.Echo "File to be deleted: " & arFiles(n).Path

' (*) to let the script delete the file, enable line below by removing the '
‘ arFiles(n).delete True

if err.number <> 0 then
  wscript.echo "Unable to delete: " & arFiles(n).path
 else
  nDeleted = nDeleted + 1
 end if
on error goto 0
next

msgbox nDeleted & " of " & ubound(arFiles)+1 _
& " eligible files were deleted"

sub SelectFiles(sPath,vKillDate,arFilesToKill)
on error resume Next

'select files to delete and add to array...

set folder = fso.getfolder(sPath)

' do not include root path
if sPath <> sRootPath then
set files = folder.files

                                  Last Edited on July 22, 2006
                                                                                                             Page 37
for each file in files
' uses error trapping around access to the
' Date property just to be safe

dtlastmodified = null
on error resume Next
dtlastmodified = file.datelastmodified
on error goto 0
if not isnull(dtlastmodified) Then
if dtlastmodified < vKillDate then
count = ubound(arFilesToKill) + 1
redim preserve arFilesToKill(count)
set arFilesToKill(count) = file
end If
end if
next
end if

for each fldr in folder.subfolders
 SelectFiles fldr.path,vKillDate,arFilesToKill
next

end sub
=======================================================

         NOTE: - this is a “cscript” script to be run from a command prompt
FileKiller.vbs
=======================================================
'****************************************************************************************
'* based on outline from Brian Adams
'* File killer
'* usage: cscript.exe filekiller.vbs FileExtension StartingLocation
'* where
'*                           "FileExtension" would simply be "mp3" or "mpg" or whatever the target is
'*    "StartingLocation" will be the starting path "C:\" or "E:\MyFolder"
'*
'* WARNING: THIS TOOL IS PROVIDED AS SAMPLE CODE ONLY - USE AT YOUR OWN RISK.
'****************************************************************************************

Option Explicit

Dim sScriptVersion, sStartingFolder, sTargetFileType, sLogFile, sUserName, sMachineName
Dim iFileCount
Dim oWSHNetwork, oWSHShell, oFSO, oLogFile

sScriptVersion = "01.23.03(01)"

If WScript.Arguments.Count > 1 Then
                      sTargetFileType = UCase(WScript.Arguments(0))
                      sStartingFolder = UCase(WScript.Arguments(1))
Else
                      WScript.Echo "usage: cscript.exe FileKiller.vbs <FileExtension> <StartingFolder> "
                      WScript.Echo " where"
                      WScript.Echo " FileExtension would simply be " & Chr(34) & "mp3" & Chr(34) & " or " & Chr(34) & "mpg"
& Chr(34) & " or whatever the target is"
                      WScript.Echo " StartingLocation will be the starting path " & Chr(34) & "C:\" & Chr(34) & " or " & Chr(34) &
"E:\MyFolder"
End If

Set oWSHNetwork = CreateObject("WScript.Network")
Set oWSHShell = CreateObject("WScript.Shell")
                                      Last Edited on July 22, 2006
                                                                                                            Page 38
Set oFSO = CreateObject("Scripting.FileSystemObject")

sLogFile = oWSHShell.ExpandEnvironmentStrings("%windir%\FKLog.txt")
Set oLogFile = oFSO.OpenTextFile(sLogFile, 8, True, 0)

sUserName = oWSHNetwork.UserName
sMachineName = oWSHNetwork.ComputerName

WriteLogHeader
KillFiles sStartingFolder, sTargetFileType
WriteLogFooter

Private Function KillFiles(sStartingFolder, sTargetFileType)
                         On Error Resume Next
  Dim oTargetFolder, oFolder, oFile

  sTargetFileType = UCase(Trim(sTargetFileType))

  If oFSO.FolderExists(sStartingFolder) Then
     Set oTargetFolder = oFSO.GetFolder(sStartingFolder)

    For Each oFile In oTargetFolder.Files
                                 If UCase(Right(oFile.Name, Len(sTargetFileType))) = sTargetFileType Then
                                          iFileCount = iFileCount + 1
                                          AppendLogFile " Deleting: " & oFile.Path
                                          oFile.Delete True
                                 End If
    Next

    For Each oFolder In oTargetFolder.SubFolders
                                 KillFiles = KillFiles(oFolder.Path, sTargetFileType)
    Next
  Else
                         AppendLogFile "ERROR: Starting Folder Not Specified or Does Not Exist (" & sStartingFolder & ")"
  End If
End Function

Private Sub WriteLogHeader
                      AppendLogFile "*****************************************************************"
                      AppendLogFile "File Killer Script Started - Version " & sScriptVersion
                      AppendLogFile "Current User: " & sUserName
                      AppendLogFile "Current Machine: " & sMachineName
                      AppendLogFile "*****************************************************************"
End Sub

Private Sub WriteLogFooter
                      AppendLogFile "*****************************************************************"
                      AppendLogFile "Deleted " & iFileCount & " Files."
                      AppendLogFile "Script Completed."
                      AppendLogFile "*****************************************************************"
                      AppendLogFile ""
                      AppendLogFile ""
End Sub

Private Sub AppendLogFile(sLine)
                     oLogFile.WriteLine Date & " " & Time & " - " & sLine
End Sub
=======================================================


                                        Last Edited on July 22, 2006
                                                                                             Page 39
ResetPassword.vbs NOTE: - this is a “cscript” script to be run from a command prompt
    Users must have credentials to be able to reset passwords
=======================================================
' ResetPassword.vbs
' VBScript program to reset the password for a user.
' The program also enables the account and expires the password.
' User must pass the NT Logon Name (sAMAccountName) of the user
' and the new password as arguments. User must have administrative
' privileges. The client must be able to make a SSL connection to
' the Domain Controller.
'' ----------------------------------------------------------------------
' Copyright (c) 2003 Richard L. Mueller
' Hilltop Lab web site - http://www.rlmueller.net
' Version 1.3 - March 18, 2004
„
' You have a royalty-free right to use, modify, reproduce, and distribute this script file
„ in any way you find useful, provided that ' you agree that the copyright owner above
„ has no warranty, obligations, or liability for such use.

Option Explicit

Dim objRootDSE, strDNSDomain, objTrans, strNetBIOSDomain
Dim strUserDN, objUser, strPassword, strUserNTName

' Constants for the NameTranslate object.
Const ADS_NAME_INITTYPE_GC = 3
Const ADS_NAME_TYPE_NT4 = 3
Const ADS_NAME_TYPE_1779 = 1

If Wscript.Arguments.Count <> 2 Then
  Wscript.Echo "Syntax Error. Correct syntax is:"
  Wscript.Echo "cscript ResetPassword.vbs UserNTName NewPassword"
  Wscript.Quit
End If

strUserNTName = Wscript.Arguments(0)
strPassword = Wscript.Arguments(1)

' Determine DNS domain name from RootDSE object.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")

' Use the NameTranslate object to find the NetBIOS domain name from the
' DNS domain name.
Set objTrans = CreateObject("NameTranslate")
objTrans.Init ADS_NAME_INITTYPE_GC, ""
objTrans.Set ADS_NAME_TYPE_1779, strDNSDomain
strNetBIOSDomain = objTrans.Get(ADS_NAME_TYPE_NT4)
' Remove trailing backslash.
strNetBIOSDomain = Left(strNetBIOSDomain, Len(strNetBIOSDomain) - 1)

' Use the NameTranslate object to convert the NT user name to the
' Distinguished Name required for the LDAP provider.
On Error Resume Next
objTrans.Set ADS_NAME_TYPE_NT4, strNetBIOSDomain & "\" & strUserNTName
If Err.Number <> 0 Then
  On Error GoTo 0
  Wscript.Echo "User " & strUserNTName _
   & " not found in Active Directory"
  Wscript.Echo "Program aborted"
                                         Last Edited on July 22, 2006
                                                                        Page 40
 Wscript.Quit
End If
strUserDN = objTrans.Get(ADS_NAME_TYPE_1779)

' Bind to the user object in Active Directory with the LDAP provider.
On Error Resume Next
Set objUser = GetObject("LDAP://" & strUserDN)
If Err.Number <> 0 Then
  On Error GoTo 0
  Wscript.Echo "User " & strUserNTName _
    & " not found in Active Directory"
  Wscript.Echo "Program aborted"
  Wscript.Quit
End If
objUser.SetPassword strPassword
If Err.Number <> 0 Then
  On Error GoTo 0
  Wscript.Echo "Password NOT reset for " &vbCrLf & strUserNTName
  Wscript.Echo "Password " & strPassword & " may not be allowed, or"
  Wscript.Echo "this client may not support a SSL connection."
  Wscript.Echo "Program aborted"
  Wscript.Quit
Else
  objUser.AccountDisabled = False
  objUser.Put "pwdLastSet", 0
  Err.Clear
  objUser.SetInfo
  If Err.Number <> 0 Then
    On Error GoTo 0
    Wscript.Echo "Password reset for " & strUserNTName
    Wscript.Echo "But, unable to enable account or expire password"
    Wscript.Quit
  End If
End If
On Error GoTo 0

Wscript.Echo "Password reset, account enabled,"
Wscript.Echo "and password expired for user " & strUserNTName

' Clean up.
Set objRootDSE = Nothing
Set objTrans = Nothing
Set objUser = Nothing
=======================================================




                                       Last Edited on July 22, 2006
                                                                                                                       Page 41
VB Script FAQ - BY
      http://www.tek-tips.com/faqs.cfm?fid=5798
By Mark D. MacLachlan, The Spiders Parlor - http://www.thespidersparlor.com

-------------------------------------------------------------------------------------------

Implementing powerful and flexible login scripts!
faq329-5798 -- Posted: 8 Apr 05 (Edited 27 May 05)
markdmac's Enterprise Ready Login Scripts

After posting an uncountable number of versions of my ever evolving login script, I finally promised myself to make an FAQ out of it, so
here it is. That's right, I am spilling all my best kept secrets right here!

Login scripts in Windows 2000 and Windows 2003 are leaps and bounds ahead of the old BAT files and KIXTART that were often used
back in the NT 4 days. If you are still using batch files, it is time for you to move ahead and see what vbscript can do for you.

Through the use of login scripts, administrators can have a central location to configure all the users in an environment.

What kind of things can you do? How about:

         1. Disconnect network drives
         2. Map network drives
         3. Map network drives based on a group membership
         4. Disconnect network printers
         5. Connect network printers
         6. Set the default printer
         7. Modify the registry
         8. Have the PC say good morning

OK, you get the idea. Almost anything is possible. Over time I have been evolving a login script that seems to be quite popular in the
forums. I've rather heavily documented it, look for the green text, so it should be easy for you to follow and modify.

I've decided that rather than replace the entire script when I add new functionality, I'm going to provide Add On code. You'll then be able
to more easily pick and choose which Add Ons to incorporate into your script. You will find the Add On section near the end of the main
script, just look for the red text. Paste any Add On code in this section.

If you use my script(s) please give credit where it is due and leave my name on it. Thanks.


CODE

'==========================================================================
'' NAME: LogonScript.vbs
' AUTHOR: Mark D. MacLachlan, The Spider's Parlor
' URL : http://www.thespidersparlor.com
' DATE : 4/10/2003
'' COMMENT: Enumerates current users' group memberships in given domain.
' Maps and disconnects drives and printers
''==========================================================================

ON ERROR RESUME NEXT

Dim WSHShell, WSHNetwork, objDomain, DomainString, UserString, UserObj, Path

Set WSHShell = CreateObject("WScript.Shell")
Set WSHNetwork = CreateObject("WScript.Network")
'Automatically find the domain name

                                          Last Edited on July 22, 2006
                                                                                                                  Page 42
Set objDomain = getObject("LDAP://rootDse")
DomainString = objDomain.Get("dnsHostName")

'Grab the user name
UserString = WSHNetwork.UserName
'Bind to the user object to get user name and check for group memberships later
Set UserObj = GetObject("WinNT://" & DomainString & "/" & UserString)

'Grab the computer name for use in add-on code later
strComputer = WSHNetwork.ComputerName

'Synchronizes the time with Server our NTP Server
WSHShell.Run "NET TIME \\Server /set /y"

'Disconnect any drive mappings as needed.
WSHNetwork.RemoveNetworkDrive "F:", True, True

'Disconnect ALL mapped drives
Set clDrives = WshNetwork.EnumNetworkDrives
For i = 0 to clDrives.Count -1 Step 2
WSHNetwork.RemoveNetworkDrive clDrives.Item(i), True, True
Next

'Give the PC time to do the disconnect, wait 300 milliseconds
wscript.sleep 300

'Map drives needed by all
'Note the first command uses the user name as a variable to map to a user share.
WSHNetwork.MapNetworkDrive "H:", "\\server\users\" & UserString,True
WSHNetwork.MapNetworkDrive "U:", "\\server\users",True
WSHNetwork.MapNetworkDrive "X:", "\\server\executables",True

'Now check for group memberships and map appropriate drives
For Each GroupObj In UserObj.Groups
Select Case GroupObj.Name
'Check for group memberships and take needed action
'In this example below, ADMIN and WORKERB are groups.
Case "Admin"
WSHNetwork.MapNetworkDrive "w:", "\\Server\Admin Stuff",True
Case "WorkerB"
WSHNetwork.MapNetworkDrive "w:", "\\Server\Shared Documents",True
'Below is an example of how to set the default printer
WSHNetwork.SetDefaultPrinter "\\ServerName\PrinterName"
End Select
Next

'Remove ALL old printers
'Enumerate all printers first, after that you can select the printers you want by performing some string checks
Set WSHPrinters = WSHNetwork.EnumPrinterConnections
For LOOP_COUNTER = 0 To WSHPrinters.Count - 1 Step 2
'To remove only networked printers use this If Statement
If Left(WSHPrinters.Item(LOOP_COUNTER +1),2) = "\\" Then
WSHNetwork.RemovePrinterConnection WSHPrinters.Item(LOOP_COUNTER +1),True,True
End If
'To remove all printers incuding LOCAL printers use this statement and comment out the If Statement above
'WSHNetwork.RemovePrinterConnection WSHPrinters.Item(LOOP_COUNTER +1),True,True
Next

'Remove a specific printer
WSHNetwork.RemovePrinterConnection "\\ServerOld\HP5si",True,True
                                         Last Edited on July 22, 2006
                                                                                               Page 43
'Install Printers
WSHNetwork.AddWindowsPrinterConnection "\\Server\HP5si"

'Add On Code goes below this line
'=====================================



'=====================================
'Add On Code goes above this line

'Clean Up Memory We Used
set UserObj = Nothing
set GroupObj = Nothing
set WSHNetwork = Nothing
set DomainString = Nothing
set WSHSHell = Nothing
Set WSHPrinters = Nothing


'Quit the Script
wscript.quit

ADD ON CODE

After applying Windows XP SP2, network printers will notify you every time a print job has completed. The
notification seems to drive most people crazy, so here is how to turn it off.

Turn Off Network Printer Notification Add On
CODE

' This section of script will prevent the balloon window
' that appears when printing to a network shared printer
' after XP Service Pack 2 is installed.
'=====================================

Path = "HKCU\Printers\Settings\EnableBalloonNotificationsRemote"
WshShell.RegWrite Path, 0 ,"REG_DWORD"

OK, so you don't see anything above to make the computer talk and your thinking.. this MARKDMAC guy is such a
liar, well yee of little faith....

You can add this code in the Add On section to make the computer say good morning to your users if you like.

Speak User Name Add On

CODE
' This Add On demonstates the Microsoft Speach API (SAPI)
'=====================================
Dim oVo
Set oVo = Wscript.CreateObject("SAPI.SpVoice")
oVo.speak "Good Morning " & WSHNetwork.username
                                         Last Edited on July 22, 2006
                                                                                                                   Page 44
Response to the speach API has been greater than I had expected. So I am enhancing the original posting to make it more friendly and less
tongue in cheek. (No pun intended)

Putting It All Together: Speach API With Greeting
CODE

'=======================================================
' Determine the appropriate greeting for the time of day.
'=======================================================
Dim HourNow, Greeting
HourNow = Hour(Now)
If HourNow >5 And HourNow <12 Then
Greeting = "Good Morning "
Elseif HourNow >12 And HourNow <16 Then
Greeting = "Good Afternoon "
Else
Greeting = "Good Evening "
End If
'=======================================================
'Find the Users Name

Dim GreetName
GreetName = SearchGivenName(objDomain,UserString)

' Use the Microsoft Speach API (SAPI)
'=====================================
Dim oVo
Set oVo = Wscript.CreateObject("SAPI.SpVoice")
oVo.speak Greeting & GreetName

'Modify This Function To Change Name Format
Public Function SearchGivenName(oRootDSE, ByVal vSAN)
' Function: SearchGivenName
' Description: Searches the Given Name for a given SamAccountName
' Parameters: RootDSE, ByVal vSAN - The SamAccountName to search
' Returns: First, Last or Full Name
' Thanks To: Kob3 Tek-Tips FAQ:FAQ329-5688

Dim oConnection, oCommand, oRecordSet

Set oConnection = CreateObject("ADODB.Connection")
oConnection.Open "Provider=ADsDSOObject;"
Set oCommand = CreateObject("ADODB.Command")
oCommand.ActiveConnection = oConnection
oCommand.CommandText = "<LDAP://" & oRootDSE.get("defaultNamingContext") & _
">;(&(objectCategory=User)(samAccountName=" & vSAN & "));givenName,sn,name;subtree"
Set oRecordSet = oCommand.Execute
On Error Resume Next
'Decide which name format to return and uncomment out
'that line. Default is first name.
'Return First Name
SearchGivenName = oRecordSet.Fields("givenName")
'Return Last Name
'SearchGivenName = oRecordSet.Fields("sn")
'Return First and Last Name
'SearchGivenName = oRecordSet.Fields("name")
On Error GoTo 0
oConnection.Close
Set oRecordSet = Nothing
                                        Last Edited on July 22, 2006
                                                                                                                  Page 45
Set oCommand = Nothing
Set oConnection = Nothing
Set oRootDSE = Nothing
End Function

Windows Version Overlay Add On
This is one of my personal favorites. Its function is to add the Windows Version as an overlay above the system
tray. Makes it really easy to know what kind of system you are dealing with. Place this code in the add on section.

Note: This section won't take affect until the user logs out and back in.

CODE
'Configure the PC to show the Windows Version and Service Pack
'as an overlay to the desktop above the System Tray
'=====================================
HKEY_CURRENT_USER = &H80000001
strComputer = WSHNetwork.Computername
Set objReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
strKeyPath = "Control Panel\Desktop"
objReg.CreateKey HKEY_CURRENT_USER, strKeyPath
ValueName = "PaintDesktopVersion"
dwValue = 1
objReg.SetDWORDValue HKEY_CURRENT_USER, strKeyPath, ValueName, dwValue
Do you hate your Start menu popping open and closing while you move the mouse within it? I prefer to have to click to open or close an
applicaiton folder under my Start Menu. If you are like me, then this Add On is for you.

Start Menu Require Click Add On
CODE
Dim smpath
smpath = "HKCU\Control Panel\Desktop\"
'the following line will REQUIRE a click in the start menu
'=====================================
WSHShell.RegWrite smpath & "MenuShowDelay","65535","REG_SZ"
'the following line will reverse what this Add On has set.
'to undo what this script has done, comment out the above line and uncomment the following
'WSHShell.RegWrite smpath & "MenuShowDelay","400","REG_SZ"
Set smpath = nothing

Clear Temporary Internet Files on Exit Add On
CODE
' This code will empty the Temp Internet Files on Exit
'=====================================
Dim tempiepath
tempiepath = "HKCU\Software\Microsoft\Windows\"

WSHShell.RegWrite tempiepath & "ShellNoRoam\MUICache\@inetcplc.dll,-4750","Empty Temporary Internet Files folder when
browser is closed","REG_SZ"

WSHShell.RegWrite tempiepath & "CurrentVersion\Internet Settings\Cache\Persistent","0","REG_DWORD"
Set tempiepath = nothing

Rename My Computer Icon with Machine Name


                                         Last Edited on July 22, 2006
                                                                                                                 Page 46
CODE
'This add on will rename the My Computer icon with the computer name
MCPath = "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
WSHShell.RegWrite MCPath & "\", strComputer, "REG_SZ"
Another of my favorite modifications is to add the Command Prompt Here option to my right click menu. Add this code to your script and
you will be able to right click on a folder and choose Command Prompt here. A command prompt will open up in that folder.

Command Prompt Here
CODE
'=====================================
' Command Prompt Here
'=====================================
On Error Resume Next
Dim cppath, cppath2
WinDir = WshShell.ExpandEnvironmentStrings("%WinDir%")

cppath = "HKCR\Directory\shell\DosHere\"
WSHShell.RegWrite cppath,"Command &Prompt Here:","REG_SZ"
WSHShell.RegWrite cppath & "command\",WinDir & "\System32\cmd.exe /k cd "& Chr(34) & "%1" &Chr(34),"REG_SZ"

cppath2 = "HKCR\Drive\shell\DosHere"
WSHShell.RegWrite cppath2,"Command &Prompt:","REG_SZ"
WSHShell.RegWrite cppath2,"Command &Prompt Here","REG_SZ"
WSHShell.RegWrite cppath2 & "command\",WinDir & "\System32\cmd.exe /k cd "& Chr(34) & "%1" &Chr(34),"REG_SZ"
'=====================================

Tired of copying a file to the clipboard, navigating Windows to another folder and pasting? Add Copy To Folder to
your right click menu.

Copy To Folder
CODE
'=====================================
' Copy To Folder
'=====================================
On Error Resume Next
Dim ctpath
ctpath = "HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers\"
WSHShell.RegWrite ctpath,"CopyTo"
WSHShell.RegWrite ctpath & "\CopyTo\","{C2FBB630-2971-11D1-A18C-00C04FD75D13}"
'=====================================

April Fools
OK, so you are feeling playful and are willing to field a plethora of phone calls and have decided to play a little
joke on your favorite users. The following code will eject the CD ROM drive. Now seriously, don't go abusing this
or I will tell your mother on you!
CODE
'Add On Code To Eject CD ROM Drive
Const CDROM = 4
For Each d in CreateObject("Scripting.FileSystemObject").Drives
If d.DriveType = CDROM Then
Eject d.DriveLetter & ":\"
End If
Next
                                       Last Edited on July 22, 2006
                                                                                                                      Page 47
Sub Eject(CDROM)
Dim ssfDrives
ssfDrives = 17
CreateObject("Shell.Application")_
.Namespace(ssfDrives).ParseName(CDROM).InvokeVerb("E&ject")
End Sub

Create Desktop Shortcut
I can't believe this one hasn't come up sooner but thankfully a Tek-Tips user asked for this. So here is the situation. You have a shared
folder on your network and you want everyone to have a shortcut to it on their desktop. Easy as pie...<insert Homer Simpson voice> Yum
pie... Sorry my brain took a vacation.

You need only edit the text in red.
CODE
SET oFSO = Wscript.CreateObject("Scripting.FileSystemObject")
strDsk = WshShell.SpecialFolders("Desktop")
' What is the label for the shortcut?
strshortcut = strDsk & "\CompanyShared.lnk"
If Not oFSO.FileExists(strshortcut) Then
SET oUrlLink = WshShell.CreateShortcut(strshortcut)
' What is the path to the shared folder?
oUrlLink.TargetPath = "\\server\CompanyShared\"
oUrlLink.Save
End If

OK, so now you have a bunch of nifty code. So what to do with it right?
OK, first copy the text and put it into notepad. Save the file as something useful like "loginscript.vbs" and use the quotes around the name
as shown here. Using the quotes in notepad will prevent notepad from adding a TXT extension on the name.

OK, now you are ready to put the script on your server. If you started navigating to the Netlogon share forget it. Time to use GPOs!

Creating a new GPO in Windows 2000 and 2003 is a bit different.

In Windows 2000, you want to right click your domain name in AD Users & COmputers. Choose properties. Click the GPO tab. Click
New. Type Login Script. Click the Edit button.

Windows 2003 users will want to open up the GPMC, Start, Administrative Tools, Group Policy Manangement Console (GPMC). Right
click your domain and choose Create and Link a GPO here. Type Login Script. Right click Login Script and choose Edit.

OK, moving on you want to maximize your performance, so if you are only going to use this GPO for the login script, right click
Administrative Templates under either the Computer or User container. Click Add/Remove Template and remove ALL templates. You
won't need them and they only beef up the size of your GPO which slows down replication.

OK, now drill down in the User Configuration. Choose Windows Settings, Scripts, Login. Double click Login.
Click Show Files. Paste your script in this location.
Close the explorer window that you just pasted into. Click the browse button and select your script. You are now done.

By default your new GPO is applied to All Authenticated Users. You may wish to modify the security settings as needed in your
environment.

All done.

As stated above, this script is constantly being evolved. I get some of my best ideas from people on Tek-Tips asking questions, so please
feel free to ask how to do something. You never know, you may just find it posted here soon afterwards.


                                         Last Edited on July 22, 2006

								
To top