Menu Content/Inhalt
Сценарии

Примеры наиболее часто используемых сценариев, которые помогут автоматизировать простейшие задачи.

Подключение сетевого принтера

' Network Printers for - Windows Logon Script.
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection "
\\Server\PrinterShare1"
objNetwork.AddWindowsPrinterConnection "
\\Server\PrinterShare2"
objNetwork.SetDefaultPrinter "
\\Server\PrinterShare1"
WScript.Quit
 

Подключение сетевого диска
С помощью vbs

Set objNetwork = CreateObject("WScript.Network")
objNetwork.RemoveNetworkDrive “Z:”
objNetwork.MapNetworkDrive "Z:" ,
\\Server\share

Либо с помошью bat

net use z: /delete
net use z: "
\\toolbox\documents"


Импорт ключей в реестр

strCommand = "regedit /s \\server\share\key.reg"
set objWshShell = WScript.CreateObject("WScript.Shell")
intRC = objWshShell.Run(strCommand, 0, TRUE)

Этот сценарий позволит сменить пароли локального администратора через сеть (при условии, что у запускающего его пользователя есть привилегии доменного администратора). Сценарий взят с http://users.pandora.be/mydotcom/program/vbs/modifypw.htm
Список имен рабочих станций расположен в c:\computerlist.txt

 strPassword = "YOURPASSWORDGOESHERE"
 Const InputFile = "c:\COMPUTERSLIST.TXT"
 Const ForReading = 1

 Set objFSO = CreateObject("Scripting.FileSystemObject")
 Set objFile = objFSO.OpenTextFile(InputFile, ForReading)
 strComputers = objFile.ReadAll
 objFile.Close
 arrComputers = Split(strComputers, vbCrLf)
 
 On Error Resume Next
 For Each strComputer In arrComputers
 
 
  ' Pinging. Inten
  Set objShell = CreateObject("Wscript.Shell")
  Set objScriptExec = objShell.Exec("ping -n 2 -w 20 " & strComputer)
  If InStr(objScriptExec.StdOut.ReadAll, "Reply") > 0 Then 

   ' User manipulation, in my case the user is "Test",
   ' change it to the local Administrator user name
   Err.Clear
   Set objUser = GetObject("WinNT://" & strComputer & "/administrator, user")
   If Err.Number Then
         WScript.Echo " " & strComputer & " - ERROR: User name not found"
    Err.Clear
   
   Else
    objUser.SetPassword strPassword
    objUser.SetInfo

    WScript.Echo " " & strComputer & " - Password successfully changed"
   End If 
  Else
  
   WScript.Echo " " & strComputer & " - ERROR: Host not responding"   
  End If

 Next

Сценарий для создания пользователей в Активной Директории с Exchange  2003.
Считывает csv файл и создает пользователей с почтовым ящиком, домашней папкой на сервере, назначает пароль из списка, включает запись и убирает требование сменить пароль при логине.
Спасибо http://downloads.techrepublic.com.com/download.aspx?docid=173470 за часы сэкономленного времени.

' -----------------------------------------------------------------
' Script: createusersfromcsv+exch+err.vbs
' Author: Scott Lowe
' Input: CSV file with layout logonname,firstname,lastname,password
' Date: January 2, 2006
' Change log:
' no changes
'------------------------------------------------------------------

Option Explicit   ' Forces declaration of variables - always use this

Dim sIOLocation
Dim sCSVFile
Dim sLogFile
Dim oInputConnection
Dim oInputRecordSet
Dim oLogObject
Dim oLogOutput
Dim oNewUser

' Variables needed for LDAP connection
Dim oRootLDAP
Dim oContainer

' Holding variables
Dim sLogon
Dim sPriEmail
Dim sFirstName
Dim sLastName
Dim sDisplayName
Dim sPassword
Dim nPwdLastSet
Dim nUserAccountControl ' Used to enable the account
Dim sLDAPdomain
Dim sLDAPExchangeServer ' See instructions before running script
Dim sLDAPmail   ' Will be set to sLogon + "@" + sLDAPdomain
Dim sLDAPmailnickname ' Will be set to sLogon
Dim sLDAPhomeMDB  ' See instructions before running script
Dim sLDAPmDBUseDefaults ' Will be set to true

' Set the full path to the Exchange server
' Broken up into separate sections for readability
' If you have multiple Exchange servers, consider including the
'      Exchange server name in your CSV file
' See accompanying instructions for quickly determining this field
'      your organization
sLDAPExchangeServer = "/o=My Organization"
sLDAPExchangeServer = sLDAPExchangeServer & "/ou=First Administrative Group"
sLDAPExchangeServer = sLDAPExchangeServer & "/cn=Configuration/cn=Servers"
sLDAPExchangeServer = sLDAPExchangeServer & "/cn=Server"

' Set the Exchange homeMDB variable
' Broken up into separate sections for readability
' If you have multiple Exchange stores, consider including the
'      store name in your CSV file
' See accompanying instructions for quickly determining this field
'      your organization
sLDAPhomeMDB = "CN= Mailbox Store,"
sLDAPhomeMDB = sLDAPhomeMDB & "CN=First Storage Group,"
sLDAPhomeMDB = sLDAPhomeMDB & "CN=InformationStore,"
sLDAPhomeMDB = sLDAPhomeMDB & "CN=Server,"
sLDAPhomeMDB = sLDAPhomeMDB & "CN=Servers,"
sLDAPhomeMDB = sLDAPhomeMDB & "CN=First Administrative Group,"
sLDAPhomeMDB = sLDAPhomeMDB & "CN=Administrative Groups,"
sLDAPhomeMDB = sLDAPhomeMDB & "CN=My Organization,"
sLDAPhomeMDB = sLDAPhomeMDB & "CN=Microsoft Exchange,"
sLDAPhomeMDB = sLDAPhomeMDB & "CN=Services,"
sLDAPhomeMDB = sLDAPhomeMDB & "CN=Configuration,"
sLDAPhomeMDB = sLDAPhomeMDB & "DC=domain, DC=local"

' Modify this to match your company's AD domain
sLDAPdomain="domain.local"

' Location of CSV file and to which log files will be written
sIOLocation = "C:\Scripts\" 'KEEP TRAILING SLASH!

' Full path to input file
sCSVFile = sIOLocation&"users.csv"
sLogFile = sIOLocation&"IO.log"

' This value is set to true
' Indicates that the user account will use default mail store rules
sLDAPmDBUseDefaults = TRUE

' Commands used to open the CSV file and select all of the records
set oInputConnection = createobject("adodb.connection")
set oInputRecordSet = createobject("adodb.recordset")
oInputConnection.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & _
    sIOLocation & ";Extended Properties=""text;HDR=NO;FMT=Delimited"""
oInputRecordSet.open "SELECT * FROM " & sCSVFile,oInputConnection

' Open the log file for writing
set oLogObject = CreateObject("Scripting.FileSystemObject")
set oLogOutput = oLogObject.CreateTextFile(sLogFile)
oLogOutput.WriteLine Now & ": Log started"

' Create a connection to the Active Directory Users container.

Set oRootLDAP = GetObject("LDAP://rootDSE")
Set oContainer = GetObject("
LDAP://cn=Users," & _
    oRootLDAP.Get("defaultNamingContext"))

' Allows processing to continue even if an error occurs (i.e. dup user)
' We put this below the CSV  and AD information since processing can
' continue with a single bad record, but not if there is a problem with
' the CSV file or AD connection
on error resume next

do until oInputRecordSet.EOF ' Reads the values (cells) in the sInputFile file.

err.clear      ' Reset the error counter

' --------- Start creating user account
' Read variable information from the CSV file
' and build everything needed to create the account
sLogon = oInputRecordSet.Fields.Item(0).value
sFirstName = oInputRecordSet.Fields.Item(1).value
sLastName = oInputRecordSet.Fields.Item(2).value
sDisplayName = sFirstName&", "&sLastName
sPassword = oInputRecordSet.Fields.Item(3).value
sPriEmail = sFirstName&"."&sLastName

' Build the User account
Set oNewUser = oContainer.Create("User","cn="&sFirstName&" "&sLastName)

oNewUser.put "sAMAccountName",lcase(sLogon)
oNewUser.put "givenName",sFirstName
oNewUser.put "sn",sLastName
oNewUser.put "UserPrincipalName",lcase(SLogon)&"@"&sLDAPdomain
oNewUser.put "DisplayName",sDisplayName
oNewUser.put "name",lcase(sLogon)

' Write this information into Active Directory so we can
' modify the password and enable the user account
oNewUser.SetInfo

'If it was successful, continue processing
If err.number = 0 Then
  oLogOutput.WriteLine Now & ": " & sLogon & ": Successfully created user account"
  ' Enable the user account
  oNewUser.Put "userAccountControl", 512
 ' Change the users password and turn off requirement to change at next login
  oNewUser.Put "pwdLastSet", -1
  oNewUser.SetPassword sPassword

  ' If the password set and account enable was successful, indicate. Otherwise, write diagnostics.
    If err.number = "0" Then
    oLogOutput.WriteLine Now & ": " & sLogon & ": Successfully created user password, enabled account and removed requirement"
  Else
    oLogOutput.WriteLine Now & ": " & sLogon & ": Password, account enable, requrement removal error : " & err.number & err.description
  End If
 
  'Create home drive
  oNewUser.Put "homeDirectory", "
\\server\share\"&sLogon
  oNewUser.Put "homeDrive", "U:"
  oNewUser.SetInfo
 
  ' If the home folder set and account enable was successful, indicate. Otherwise, write diagnostics.
  If err.number = "0" Then
    oLogOutput.WriteLine Now & ": " & sLogon & ": Successfully created user home folder"
  Else
    oLogOutput.WriteLine Now & ": " & sLogon & ": Home folder setting error : " & err.number & err.description
  End If

  ' Build and write the users Exchange attributes
  oNewUser.put "mDBUseDefaults", sLDAPmDBUseDefaults
  oNewUser.put "mail", lcase(SPriEmail)&"@"&sLDAPdomain
  oNewUser.put "msExchHomeServerName", sLDAPExchangeServer
  oNewUser.put "mailnickname", lcase(sLogon)
  oNewUser.put "homeMDB", sLDAPhomeMDB
  oNewUser.SetInfo
 
  ' If the Exchange attributes were successful, indicate.  Otherwise, write diagnostics.
  If err.number = "0" Then
    oLogOutput.WriteLine Now & ": " & sLogon & ": Successfully created user's Exchange attributes"
  Else
    oLogOutput.WriteLine Now & ": " & sLogon & ": Exchange attributes error : " & err.number & err.description
  End If

Else
  oLogOutput.WriteLine Now & ": " & sLogon & ": Error creating account: " & err.number & err.description
End If

' --------- End of user account creation
' Move ahead to the next record
oInputRecordSet.movenext
Loop

' Close the log file
oLogOutput.WriteLine Now & ": Input ended"
oLogOutput.Close