This page has been robot translated, sorry for typos if any. Original content here.

Scripts for system administrators, Useful scripts for Win2003



  • To connect a network drive
  • To connect the printer
  • Check for changes to parameters in AD and send to email or sharepoint list
  • Script for removing terminal license on clients, every 30 days
  • Script to combat mail.ru-agent
  • The script makes a backup of the system and uploads it to the FTP
  • blocks / unblocks users in AD, taking a list of their full name from a specific file
  • copy file to custom roaming profiles
  • The script searches for all controllers for users who have not logged in for more than 90 days and disable them
  • batch file (closefl.bat) closes all files opened by users on the network on your computer
  • The script to notify the user about the termination of the account in the domain for 10 days
  • Script for searching in the directory of users with a limited validity of the account and export to a file
  • Script ykiy pervіryae є new users і і ідсилає ім лист в каз м м
  • Set or clear the checkbox “allow remote access to this computer”
  • turn off - turn on the adapter
  • Evenarization of all machines in the domain
  • Determining When An Expiration Date For A User Account
  • Determining When a User Account Expires
  • Recursively sets all users of the domain attribute "User must change password on next logon"
  • Getting the SID (s) of a computer from AD
  • Search accounts in ActiveDirectory with expired passwords
  • Interviews computers for which user is currently logged in.
  • Monitors the system log and notifies you of changing browser settings
  • Script for restarting ADSL moped D-link DSL-2640U
  • script to create user accounts from the list. (txt, xls)
  • Restart apache, mysql, cron, sendmail services


  • You open a notebook, copy the code there and save the document with the extension .vbs. Further, if a network without domains, copy this file to autoload for each PC. If a network with a domain, then create a group policy (in AD), where you insert this file in the startup parameters. Next, when you connect or restart your account, the script will run






    To connect a network drive:
     Set WshNetwork = CreateObject ("WScript.Network") 'Creating an object of the type Network Set Drives = WshNetwork.EnumNetworkDrives c = 0' Temporary check for at least one network drive!  i = 0 While i <= Drives.Count-1 'Check for network presence c = 1' MsgBox "You have a network drive" & Drives.Item (i) & "-" & Drives.Item (i + 1) i = i + 2 Wend if c = 0 then 'MsgBox "There are no connected drives"' MsgBox "Attempting to mount a network drive" 'Set WshNetwork = CreateObject ("WScript.Network") WshNetwork.MapNetworkDrive \ Nameserver \ folder name "End if 





    To connect the printer:
     Set WshNetwork = WScript.CreateObject ("WScript.Network")
     WshNetwork.AddWindowsPrinterConnection "\\ name print server \ printer name"
    
    





    Check the changes in the parameters in AD and send a notification to the email or Sharepoint list:


    / * =============================================== ========
    '
    'Script Information: Sending a Message to the Administrator
    'when changing data in AD, sending a message is possible
    'to email or create a task in MOSS 2007
    '
    'Author: Korotenko Vladimir SDC 2008 Voronezh
    Originally created: 04/15/2008 - 11:01:47
    'Original path: untitled.vbs
    'Description: Dumping the domain schema and comparing
    'with the previous copy for receiving changes and the subsequent
    'alert
    '
    '================================================ =======
    * /




    // Script Settings Section
    var SmtpHost, SmtpPort, MailSubject, MailTo, MailFrom, TextBody;
    var DumpCmdLine, WinDiff, DumpFile, DumpFileOld, WorkingFolder;
    var DiffFile, DiffMessage;
    var SpListGuid, SpHost, UseSp;

    SmtpHost = "comp1"; // mail server for sending messages
    SmtpPort = 25; // port of the mail server
    MailSubject = "Make changes to the organization chart"; // message header
    MailTo = "vkoroten@ot.comch.ru"; // Address of the recipient
    MailFrom = "vkoroten@ot.comch.ru"; // Sender's address
    DumpCmdLine = "c: \\ windows \\ system32 \\ ldifde.exe"; // command line to dump their AD data
    WinDiff = "c: \\ temp \\ windiff.exe"; // Program for comparison 2
    DumpFile = "schema.ldf"; // Name of the file to save
    DumpFileOld = "schemaOld.ldf"; // File name 2 for comparison
    WorkingFolder = "c: \\ temp \\"; // working folder for temporary files

    DiffFile = "diff.log"; // File for comparison results
    DiffMessage = "1 files listed"; // string we are looking for when files are different

    SpListGuid = "{3D9B5EFB-C0C5-434C-B1DA-61FEA6E9D63B}";
    SpHost = "http: // portal4";
    UseSp = true; // send messages to the Share Point list

    // End of settings section

    / ************************************************* ********************
    Code change only in the case of a deep understanding of what you are doing
    and most importantly how are you doing !!!!!!!!!
    ************************************************** ******************** /

    var file, wsh;
    // create object for work

    file = WScript.CreateObject ("Scripting.FileSystemObject");

    if (file.FileExists (WorkingFolder + DumpFileOld))
    file.DeleteFile (WorkingFolder + DumpFileOld);

    if (file.FileExists (WorkingFolder + DumpFile))
    file.MoveFile (WorkingFolder + DumpFile, WorkingFolder + DumpFileOld)

    wsh = WScript.CreateObject ("WScript.Shell");

    wsh.Run (DumpCmdLine + "-f" + WorkingFolder + DumpFile, 1,1);
    TrimUnused (WorkingFolder + DumpFile);

    if (file.FileExists (WorkingFolder + DumpFileOld))
    CheckChanges (WorkingFolder + DumpFile, WorkingFolder + DumpFileOld);




    // Check for difference 2 files
    function CheckChanges (pathFrom, pathTo)
    {
    var cmd;
    // WinDiff.Exe output.ldf schemaOld.ldf -Sx logcmd
    cmd = WinDiff + "" + pathFrom + "" + pathTo + "-Sx" + WorkingFolder + DiffFile;
    wsh.Run (cmd, 1,1);
    objFile = file.OpenTextFile (WorkingFolder + DiffFile, 1);
    var buff = new String ();
    buff = objFile.ReadAll ();
    objFile.Close ();
    var arr = new Array ();
    arr = buff.split ("\ r \ n");

    for (var i = 0; i <arr.length; i ++)
    {
    // Check whether the files are different, if so send a message

    if (arr [i] .indexOf (DiffMessage)> - 1)
    {
    var d = new Date ();
    TextBody = "Changes detected in the schema. Comparison time:" + d.toString ();
    SendMessage ();
    }
    }
    }



    // Remove the lines with frequently changed attributes
    function TrimUnused (name)
    {
    var ForReading = 1;
    var ForWriting = 2;
    var objFSo, objFile;


    objFSo = new ActiveXObject ("Scripting.FileSystemObject");
    objFile = objFSo.OpenTextFile (name, ForReading);
    var strContents = new String ();
    strContents = objFile.ReadAll ();
    objFile.Close ();

    var arr = new Array ();
    arr = strContents.split ("\ r \ n");

    objFile = objFSo.OpenTextFile (name, ForWriting);

    for (var i = 0; i <arr.length; i ++)
    {
    if (arr [i] .indexOf ("lastLogon") == -1) {
    objFile.WriteLine (arr [i]);
    }
    }
    objFile.Close ();
    }



    // Send a message to the address. All parameters must be specified in the global variables section.

    function SendMessage () {

    if (UseSp)
    {
    NewMessage (SpListGuid, SpHost, TextBody);
    return;
    }
    var objEmail = new ActiveXObject ("CDO.Message");
    objEmail.From = MailFrom;
    objEmail.To = MailTo;

    objEmail.Subject = MailSubject;
    objEmail.Textbody = TextBody;
    objEmail.MimeFormatted = true;
    objEmail.BodyPart.Charset = "windows-1251";
    objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2;
    objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = SmtpHost;
    objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = SmtpPort;
    objEmail.Configuration.Fields.Update ();
    objEmail.Send ();

    }

    // create a new message in the Sharepoint list
    function NewMessage (list, hostName, message)
    {
    var web, req, batch;
    web = new ActiveXObject ("MSXML2.XMLHTTP.3.0");

    batch = "<Batch ListVersion = '0'> <Method ID = '1' Cmd = 'New'> <Field Name = 'Title'>" + message + "</ Field> </ Method> </ Batch>" ;

    var req = "<? xml version = '1.0' encoding = 'utf-8'?> <soap: Envelope xmlns: xsi = 'http: //www.w3.org/2001/XMLSchema-instance' xmlns: xsd = 'http://www.w3.org/2001/XMLSchema' xmlns: soap = 'http: //schemas.xmlsoap.org/soap/envelope/'> <soap: Body> <UpdateListItems xmlns = 'http: // schemas.microsoft.com/sharepoint/soap / '> ";
    req + = "<listName>" + list + "</ listName>";
    req + = "<updates>" + batch + "</ updates> </ UpdateListItems> </ soap: Body> </ soap: Envelope>";


    var r = hostName + "/_vti_bin/Lists.asmx?op=UpdateListItems";
    web.Open ("POST", r, False);
    web.setRequestHeader ("Content-Type", "text / xml; charset = utf-8");
    web.setRequestHeader ("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
    web.send (req);

    //'WScript.Echo req
    //'WScript.Echo Chr (13) & Chr (10)
    //'WScript.Echo web.responseText

    }





    Script for removing terminal license on clients, every 30 days:

    'If necessary, deletes the registry key in which temporary licenses are stored, if 30 days have passed.
    Option Explicit
    Dim iCount, dDat, dReadDat, strPath, strRegKey 'variable declaration
    Dim fso, fLogFile, wshSysEnv, wshShell 'object declaration

    dDat = date 'we get the current date
    err.clear 'yf just in case we make a stack of errors

    on error resume next 'After this error messages are not displayed

    'Create a Shell object
    Set wshShell = WScript.CreateObject ("WScript.Shell")
    'Create an Environment object in which the desired system variable is located
    Set wshSysEnv = WshShell.Environment ("PROCESS")
    'Take out the system variable (the path to the Windows folder) and put it in a string variable for further use
    strPath = wshSysEnv ("WINDIR")

    'Create a file system access object and read file access object
    Set fso = CreateObject ("Scripting.FileSystemObject")
    set fLogFile = fso.OpenTextFile (strPath & "\ LiDelDat.alx", 1, false)

    'The main condition for deleting or deleting a registry branch
    If err.number <> 0 then
    'Perform registry branch removal procedure
    Call DelLicense

    'Record the last date the license was removed to the log file, overwriting the entry in it
    Call WriteToLog
    Else
    'Read from the file and compare the date of the last deletion of the license with the current date
    dReadDat = CDate (fLogFile.ReadLine ())

    'Must have (dDat - dReadDat)
    If (dDat - dReadDat)> 29 Then
    'Perform registry branch removal procedure
    Call DelLicense

    'Record the last date the license was removed to the log file, overwriting the entry in it
    Call WriteToLog
    End if
    End if

    'Destroy all unnecessary more objects
    Set WshShell = Nothing
    Set wshSysEnv = Nothing
    Set fso = Nothing

    '************************************************* ***********
    'Procedures
    '************************************************* ***********
    'License removal procedure
    Sub Del License ()
    'Remove license-plug one by one
    on error resume next
    err.clear

    for iCount = 0 to 9
    strRegKey = "HKLM \ SOFTWARE \ Microsoft \ MSLicensing \ Store \ LICENSE00" & iCount & "\"
    WshShell.RegDelete (strRegKey)

    If err.number <> 0 then
    err.clear
    End if
    next

    'Remove the main section subkey
    WshShell.RegDelete ("HKLM \ SOFTWARE \ Microsoft \ MSLicensing \ Store \")
    if err.number <> 0 then err.clear

    WshShell.RegDelete ("HKLM \ SOFTWARE \ Microsoft \ MSLicensing \ HardwareID \")
    if err.number <> 0 then err.clear

    'Delete the main section
    WshShell.RegDelete ("HKLM \ SOFTWARE \ Microsoft \ MSLicensing \")
    if err.number <> 0 then err.clear

    End sub

    'The procedure for writing the date of the last license removal to a file
    Sub WriteToLog ()
    err.clear

    'Create an object of access to the desired file to write overwriting previous records
    set fLogFile = fso.OpenTextFile (strPath & "\ LiDelDat.alx", 2, true)

    'Write to the file the date of registry cleaning
    fLogFile.Write (Date)

    set fLogFile = nothing 'destroy object
    End sub





    Script to combat mail.ru-agent:

    Const DeleteReadOnly = TRUE

    Set WshShell = WScript.CreateObject ("Wscript.Shell")
    Set WshSysEnv = WshShell.Environment ("Process")

    Set objFSO = CreateObject ("Scripting.FileSystemObject")
    agentFile = WshSysEnv ("userprofile") + "\ Application Data \ Mail.Ru \ Agent \ magent.exe"


    If objFSO.FileExists (agentFile) Then

    objFSO.DeleteFile (agentFile), DeleteReadOnly


    if err.number = 0 then
    Set objEmail = CreateObject ("CDO.Message")

    objEmail.From = "killer@kontora.ru"
    objEmail.To = "admin@kontora.ru"
    objEmail.Subject = "Mail.ru-agent"
    objEmail.Textbody = "Dear system administrators, I notify you that the enemy mail.ru agent from" + WshSysEnv ("userprofile") has been destroyed
    objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
    "ip mail server"
    objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    objEmail.Configuration.Fields.Update
    objEmail.Send

    end if

    end if





    The script makes a backup of the system and uploads it to the FTP:

    strComputer = "."
    Set WshShell = WScript.CreateObject ("WScript.Shell")
    strCommand = "C: \ WINDOWS \ system32 \ ntbackup.exe backup @C: \ cmd \ Back-UP-Drive-C.bks / a / v: no / r: no / rs: no / hc: off / m normal / j Back-UP-Drive-C / l: s / f D: \ Back-Up \ Backup-drive-c.bkf "
    WshShell.Run strcommand, 1, true

    Set objWMIService = GetObject ("winmgmts: \\" & strComputer & "\ root \ cimv2")
    Set colItems = objWMIService.ExecQuery ("Select * from Win32_LocalTime")

    For Each objItem in colItems
    strCommand = "C: \ Arch \ 7z.exe a D: \ Back-Up \ Backup-dc-srv-01-DayOf-Week -" & objItem.DayOfWeek & ". 7z D: \ Back-Up \ *. bkf -t7z -m0 = BCJ2 -m1 = LZMA: d23 -m2 = LZMA: d19 -m3 = LZMA: d10M -mb0: 1 -mb0s1: 2 -mb0s2: 3 "
    Next
    WshShell.Run strcommand, 1, true
    strCommand = "ftp -s: C: \ CMD \ ctp-command.txt"
    WshShell.Run strcommand, 1, true





    The script blocks / unblocks users in AD, takes a list of their full names from a specific file, and notifies the administrator by mail about the results:

    Dim Mlogins (9000), MAdspath (9000), MFullName (9000)
    Dim objFileSystem, objInputFileFromKardy, strData
    Set objFSO = CreateObject ("Scripting.FileSystemObject")
    Const OPEN_FILE_FOR_READING = 1

    'Specify the domain
    Const strDomainName = "<domain name for example domain.com>"
    'Specify OU in AD, inside which we will search
    Const strStartOU = "Domain Users"
    strDomainDN = "DC =" & Replace (strDomainName, ".", ", DC =")

    '--------------------- Receiving data --------------------
    Set objConnection = CreateObject ("ADODB.Connection")
    objConnection.Open "Provider = ADsDSOObject;"
    Set objCommand = CreateObject ("ADODB.Command")
    objCommand.ActiveConnection = objConnection
    objCommand.CommandText = "<LDAP: // OU =" & strStartOU & "," & strDomainDN & ">; (& (objectCategory = person) (objectClass = user)); ADsPath; subtree"
    objCommand.Properties ("Page Size") = 4000

    Set objRecordSet = objCommand.Execute


    '------ Indexing --------
    index = 0
    While Not objRecordset.EOF
    strADsPath = objRecordset.Fields ("ADsPath")
    Set objUser = GetObject (strADsPath)
    MFullName (index) = objUser.DisplayName & ""
    Mlogins (index) = objUser.sAMAccountName
    MAdspath (index) = strADsPath
    index = index + 1
    objRecordset.MoveNext

    Wend
    objConnection.Close

    index = index-1
    maxindex = index

    'Path to the file in which the list of names of people is stored whose accounts need to be opened / closed
    strFileOfFiried = "d: \ file_of_firied.txt"

    Set objFileSystem = CreateObject ("Scripting.fileSystemObject")
    Set objInputFileFromKardy = objFileSystem.OpenTextFile (strFileOfFiried, OPEN_FILE_FOR_READING)
    'We drive the contents of the file into the array
    inputDataFromFiried = Split (objInputFileFromKardy.ReadAll, vbNewline)
    'Zero results lists
    UserDisables = ""
    UserUpdated = ""
    UserNoFound = ""
    UserDuplicated = ""
    ii = 0


    For each strFULL In inputDataFromFiried
    if Len (strFULL)> 5 then
    'reset the counter of found matches
    e = 0
    '1st field: select the user's full name from the line
    strFIO = Left (strFULL, InStr (strFULL, ";") - 1)
    'We break in parts full name
    Familia = Left (strFIO, (Instr (strFIO, "") -1))
    N = Trim (mid (strFIO, Instr (strFIO, "")))
    Imya = Left (N, (Instr (N, "") -1))
    Otchestvo = Trim (mid (N, Instr (N, "")))
    'Putting together the full name
    strFIO = Familia & "" & Imya & "" & Otchestvo

    index = maxindex
    While index> 1

    'We break in parts full name in AD

    AdFamilia = ""
    Admya = ""
    AdOtchestvo = ""
    AdFamilia = Left (MFullName (index), (Instr (MFullName (index), "") -1))
    if Len (Trim (mid (MFullName (index), Instr (MFullName (index), ""))))> 1 then
    AdN = Trim (mid (MFullName (index), Instr (MFullName (index), "")))
    if Len (Left (AdN, (Instr (AdN, ""))))> 1 then
    AdImya = Left (AdN, (Instr (AdN, "") -1))
    if Len (Trim (mid (AdN, Instr (AdN, ""))))> 1 then
    AdOtchestvo = Trim (mid (AdN, Instr (AdN, "")))
    end if
    end if

    end if


    'Putting together the full name
    AdstrFIO = AdFamilia & "" & AdImya & "" & AdOtchestvo
    AdstFIO1 = AdImya & "" & AdOtchestvo & "" & AdFamilia
    AdstrFIO2 = AdImya & "" & AdFamilia & "" & AdOtchestvo
    'Wscript.Echo AdstrFIO

    if (StrFIO = AdstrFIO) or (StrFIO = AdstrFIO1) or (StrFIO = AdstrFIO2) then
    e = e + 1
    Mindex = index
    end if
    index = index-1
    Wend


    if e = 1 then
    'block login in AD
    LockUser (Mlogins (Mindex))
    UserDisables = UserDisables & "User:" & strFIO & "is disabled" & vbCrLf
    end if
    'Do not block / open, because we found several identical names
    if e> 1 then
    UserNoFound = UserNoFound & "User:" & strFIO & "is found more than 1 times" & vbCrLf
    end if
    'Do not block / open, because User is not found
    if e = 0 then
    UserDuplicated = UserDuplicated & "User:" & strFIO & "is not found" & vbCrLf
    end if

    end if


    Next






    'if there is any result, then
    if (len (UserDisables) + len (UserNoFound) + len (UserDuplicated)> 10) then
    'start sending mail

    Set objNetwork = CreateObject ("Wscript.Network")
    objComputerName = objNetwork.ComputerName
    objUserName = objNetwork.UserName
    Set objMessage = CreateObject ("CDO.Message")
    objMessage.From = "<e-mail from whom mail is sent>"
    objMessage.To = "<e-mail to whom mail is sent>"
    objMessage.Subject = "Email subject"

    'Put the coding
    objMessage.bodypart.charset = "koi8-r"
    objMessage.TextBody = UserDisables & vbCrLf & UserNoFound & vbCrLf & UserDuplicated
    objMessage.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    'Name or IP of Remote SMTP Server
    objMessage.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "<server smtp address>"
    'Server port (typically 25)
    objMessage.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    objMessage.Configuration.Fields.Update
    '== End remote SMTP server configuration section ==

    objMessage.Send


    end if



    objInputFileFromKardy.Close
    Set objFileSystem = Nothing
    Sub LockUser (strText)
    'in this line, the value is TRUE - the user's disability, FALSE - opens the user
    strDisableAccount = TRUE

    strUserLogin = strText
    set objUser = GetObject ("WinNT: // <domain> /" & strUserLogin & ", user")


    if strDisableAccount = true then
    objUser.AccountDisabled = strDisableAccount
    objUser.Description = "Account is Disabled because of firing" & "at" & "" & Date ()
    objUser.SetInfo
    end if

    if strDisableAccount = FALSE then
    objUser.AccountDisabled = strDisableAccount
    objUser.Description = "Account is Opened by script" & "at" & "" & Date ()
    objUser.SetInfo
    end if


    End sub





    This script is intended for copying a file into user relocatable profiles:

    // ************************************************ ******************************
    // JScript 2004 Shs
    // This script is designed to copy the file to the user roaming profiles
    // (Add a shortcut to the user menu)
    // ************************************************ *******************************
    //
    //
    // ************************************************ ******************************
    // Recursive transition function in all subdirectories starting from the given one (PolFldr)
    // and copy the specified file (ScriptName) to the specified folders (FldrName)
    // ************************************************ *******************************
    function LoopSubFolders (PolFldr, DeepCount)
    {
    var SubFolders, // Collection of system policy subcatalogs
    fsoPolFldr, // object to access the folder
    CurFldr; // current folder

    DeepCount ++;
    //WScript.Echo(DeepCount);
    if (DeepCount <DeepLimit)
    {
    fsoPolFldr = FSO.GetFolder (PolFldr);
    // Get a collection of system policy catalog subdirectories
    SubFolders = new Enumerator (fsoPolFldr.SubFolders);
    //
    for (;! SubFolders.atEnd (); SubFolders.moveNext ())
    {
    CurFldr = SubFolders.item ();
    if (CurFldr.Name == FldrName)
    {
    try {
    WScript.Echo (CurFldr.Path + "\\" + ScriptName);
    //WScript.Echo(Path2Scripts + "\\" + ScriptName);
    FSO.CopyFile (Path2Scripts + "\\" + ScriptName, CurFldr.Path + "\\" + ScriptName, true)
    }
    catch (e)
    {// handle possible errors
    var Msg;
    if (e! = 0) Msg = "Error -" + e.description
    else Msg = "Ok";
    WScript.Echo (Msg);
    }
    }
    // recursive call
    LoopSubFolders (CurFldr, DeepCount);
    } // end for
    } // end if
    }
    // ************************************************ *********************************

    //
    //


    // ************************************************ *********************************

    // stub
    // ************************************************ *********************************

    // here will be the code getting from the command line parameters
    // 1) the name of the file being distributed
    // 2) directory names in each profile to which the distributed file will be copied
    // ************************************************ *********************************

    var ScriptName = "Updating the working menu.lnk",
    FldrName = "Main Menu"; // Name of the required subfolder in the profile (we will copy the shortcut file into it)
    // ************************************************ *********************************
    **




    // ************************************************ *********************************
    *
    // Declare global variables
    // ************************************************ *********************************
    *
    var FSO, // FileSystemObject Object
    Path2Scripts, // Path to the file being distributed (it is assumed that the files are in the same folder as this file)
    DeepCount, // Recursion Depth Count
    DeepLimit, // Limiting the depth of recursion
    PolF; // The root from which to start searching and distributing files to the following folders
    // ************************************************ *******************************=
    *
    PolF = "\\\\ DC \\ UserFolders \\ OZI"; ////
    // Create a FileSystemObject object;
    FSO = WScript.CreateObject ("Scripting.FileSystemObject");
    DeepCount = 0;
    Path2Scripts = FSO.GetParentFolderName (FSO.GetFile (WScript.ScriptFullName));
    // Restrict the depth of recursive calls
    DeepLimit = 4;
    LoopSubFolders (PolF, DeepCount);





    Eventarization of all machines in the domain:

    dim strclass, objAD, obj
    dim invdate
    dim constmb, constgb, sizegb
    dim compname, temp, compad
    constmb = 1048576
    constgb = 1073741824
    strclass = array ("win32_ComputerSystem", "win32_bios", "win32_processor", _
    "win32_diskdrive", "win32_videocontroller", "win32_NetworkAdapter", _
    "win32_sounddevice", "win32_SCSIController", "win32_printer")

    set objAD = getobject ("LDAP: // CN = Computers, DC = aaa, DC = bbb, DC = ccc")
    objAD.filter = array ("computer")
    on error resume next
    for each obj in objAD
    CompAD = right (obj.name, len (obj.name) -3)
    invdate = date
    temp = "<html>" + chr (10) + "Collect date:" & invdate & "<table>" + chr (10)
    compname = ""
    'on error error next
    set objWMIService = GetObject ("winmgmts: //" & CompAD & "/ root \ cimv2")
    i = 0
    s = 0
    d = 0
    q = 0
    'sizegb = ""
    for a = 0 to 8
    Set colitems = objwmiservice.instancesof (strclass (a))
    for each objitem in colitems
    select case a
    case 0
    temp = temp + "<tr> <td>"
    temp = temp + "Computer name" + "</ td> <td>" + objitem.name + "</ td>" + chr (10)
    temp = temp + "</ tr>" + chr (10)
    temp = temp + "<tr> <td>"
    temp = temp + "RAM" + "</ td> <td>" + cstr (round (objitem.totalphysicalmemory / constmb)) + "MB </ td>" + chr (10)
    temp = temp + "</ tr>" + chr (10)
    temp = temp + "<tr> <td>"
    temp = temp + "Computer Model" + "</ td> <td>" + objitem.model + "</ td>" + chr (10)
    temp = temp + "</ tr>" + chr (10)
    compname = objitem.name
    case 1
    temp = temp + "<tr> <td>"
    temp = temp + "Motherboard" + "</ td> <td>" + objitem.SMBIOSBIOSVersion + "</ td>" + chr (10)
    temp = temp + "</ tr>" + chr (10)
    temp = temp + "<tr> <td>"
    temp = temp + "BIOS" + "</ td> <td>" + objitem.caption + "</ td>" + chr (10) + "<td>" + chr (10) + "</ td>"
    temp = temp + "</ tr>" + chr (10)
    case 2
    s = s + 1
    temp = temp + "<tr>" + chr (10) + "<td>"
    temp = temp + "Processor" + cstr (s) + "</ td>" + chr (10) + "<td>" + objitem.name + "Frequency" + cstr (objitem.CurrentClockSpeed) + chr (10) + " </ td> "
    temp = temp + "</ tr>" + chr (10)
    case 3
    i = i + 1
    temp = temp + "<tr>" + chr (10) + "<td>"
    if objitem.size> 0 then '= nill then
    sizegb = cstr (round (objitem.size / constgb, 2))
    else
    sizegb = cstr (0)
    end if
    temp = temp + "Hard disk" + cstr (i) + "</ td>" + chr (10) + "<td>" + objitem.model + "" + sizegb + "GB </ td>" + chr ( ten)
    temp = temp + "</ tr>" + chr (10)
    case 4
    temp = temp + "<tr>" + chr (10) + "<td>"
    temp = temp + "Video Monitor" + "</ td>" + chr (10) + "<td>" + objitem.caption + chr (10) + "</ td>"
    temp = temp + "</ tr>" + chr (10)
    case 5
    if objitem.adaptertype = 0 and objitem.netconnectionstatus = 2 then
    temp = temp + "<tr>" + chr (10) + "<td>"
    temp = temp + "network adapter" + "</ td>" + chr (10)
    temp = temp + "<td>" + objitem.name + chr (10) + "</ td>"
    temp = temp + "</ tr>" + chr (10)
    end if
    case 6
    temp = temp + "<tr>" + chr (10) + "<td>"
    temp = temp + "Sound card" + "</ td>" + chr (10)
    temp = temp + "<td>" + objitem.caption + chr (10) + "</ td> </ tr>" + chr (10)
    case 7
    temp = temp + "<tr>" + chr (10) + "<td>"
    temp = temp + "SCSI Adapter" + "</ td>" + chr (10)
    temp = temp + "<td>" + objitem.manufacturer + "" + objitem.caption + chr (10) + "</ td> </ tr>" + chr (10)
    case 8
    d = d + 1
    temp = temp + "<tr>" + chr (10) + "<td>"
    temp = temp + "Printer" + cstr (d) + "</ td>" + chr (10) + "<td>" + objitem.name + chr (10) + "</ td>"
    temp = temp + "</ tr>" + chr (10)
    end select
    next
    next
    'Final part
    temp = temp + "</ table> </ html>"
    'Write file
    Dim fso, tf
    Set fso = CreateObject ("Scripting.FileSystemObject")
    Set tf = fso.CreateTextFile ("\\ servak ​​\ comp \" & compname & ". Htm", True)
    tf.Write (temp)
    tf.Close
    next





    Determining the Expiration date for a user account:

    On Error Resume Next
    Set objUser = GetObject _
    ("LDAP: // cn = myerken, ou = management, dc = fabrikam, dc = com")

    dtmAccountExpiration = objUser.AccountExpirationDate

    If err.number = -2147467259 Or _
    dtmAccountExpiration = "1/1/1970" Then
    WScript.echo "No account expiration specified"
    Else
    WScript.echo "Account expiration:" & _
    objUser.AccountExpirationDate
    End if





    Determining When My Account Active Directory User Account Expires:
      On Error Resume Next 
    Set objUser = GetObject _
    ("LDAP: // cn = MyerKen, ou = Management, dc = NA, dc = fabrikam, dc = com")
    dtmAccountExpiration = objUser.AccountExpirationDate

    If Err.Number = -2147467259 Or dtmAccountExpiration = "1/1/1970" Then
    WScript.Echo "No account expiration specified"
    Else
    WScript.Echo "Account expiration:" & objUser.AccountExpirationDate
    End if





    The script recursively sets the attribute "User must change password on next logon" to all domain users: PS For correct operation, you need to define the domain name from the LDAP perspective in the strMyDomain variable — that is, Replace all points with "DC =". Thus, the domain argo.com turns into DC = argo, DC = com into the variable strMyOU you must put the name of the Organization Unit, the users of which must be subjected to the procedure for changing the password.

    Dim strMyOU
    Dim strMyDomain

    Dim objOU, objUser
    Dim strContainer, strLastUser

    strMyOU = "argo"
    strMyDomain = "DC = argo, DC = com"

    sub recurs (ou)
    strContainer = "OU =" + ou + "," + strMyDomain
    set objOU = GetObject ("LDAP: //" & strContainer)
    For each objUser in objOU
    strLastUser = objUser.Get ("name")
    If objUser.Class = "organizationalUnit" Then
    recurs (strLastUser + ", OU =" + ou)
    Elseif objUser.Class = "user" Then
    objUser.Put "pwdLastSet", 0
    objUser.SetInfo
    end if
    next
    end sub

    recurs strMyOU

    WScript.Quit





    Getting the SID (s) of a computer from AD:

    On Error Resume Next
    Dim Tmp, x, b, Sid
    Set objSysInfo = CreateObject ("ADSystemInfo")
    strComputerDN = objSysInfo.ComputerName
    Set objCmp = GetObject ("LDAP: //" & strComputerDN)
    Sid = objCmp.objectSID
    gSID = "S-1-5 -" & Convert (16,19) & "-" & Convert (12,15) & "-" & Convert (8,11) & "-" & Convert (4.7) & "-" & Convert (0.3)
    Set objGroup = Nothing

    function Convert (u, l)
    Tmp = ""
    For x = UBound (Sid) -u to UBound (Sid) -l Step -1
    b = AscB (MidB (SID, x + 1))
    Tmp = Tmp & Hex (b \ 16) & Hex (b And 15)
    Next
    Convert = Clng ("& H" & Tmp)
    end function
    wscript.echo (gSID)





    Search for accounts in ActiveDirectory with expired passwords: If the NetBIOS domain name differs from the DNS to the first point, then instead of the string dom = getObject ("LDAP: //" & DC) .get ("Name"), set the desired value

    on Error resume next

    DC = getObject ("LDAP: // RootDSE") .get ("defaultNamingContext")
    dom = getObject ("LDAP: //" & DC) .get ("Name")
    pwAge = getObject ("WinNT: //" & dom) .get ("MaxPasswordAge") / 86400

    set objConnection = createObject ("ADODB.Connection")
    objConnection.open "Provider = ADsDSOObject;"

    set objCmd = createObject ("ADODB.Command")
    objCmd.ActiveConnection = objConnection

    '- Command for searching computer accounts
    'cmd = "<LDAP: //" & DC & ">; (objectClass = computer); distinguishedName, samAccountName; subtree"

    '- Command for searching user accounts
    cmd = "<LDAP: //" & DC & ">; (objectCategory = person); distinguishedName, samAccountName; subtree"

    objCmd.CommandText = cmd

    set col = objCmd.execute

    if col.recordCount> 0 then
    col.moveFirst
    while not col.EOF
    dn = col.fields (0) .value
    acc=col.fields(1).value

    set obj=getObject("LDAP://" & dn)
    accCtrl=obj.get("userAccountControl")

    if (accCtrl and &h10000)=0 then
    pwChg=obj.PasswordLastChanged
    if (Err.Number<>0) then
    E=CStr(Err.Number) & " " & Err.Description
    ' WScript.echo acc & space(16-len(acc)) & " - Error : " & E
    Err.clear
    else
    if (now-pwChg)>pwAge then
    WScript.echo acc & space(16-len(acc)) & " - Expired : " & (pwChg+pwAge)
    else
    ' WScript.echo acc & space(16-len(acc)) & " - Expire on : " & (pwChg+pwAge)
    end if
    end if
    else
    ' WScript.echo acc & space(16-len(acc)) & " - Never Expire"
    end if
    col.moveNext
    wend
    end If

    objConnection.close





    Скрипт опрашивает компьютеры домена на предмет того, какой пользователь залогинен в данный момент на каждом компьютере :

    On Error Resume Next

    Const ADS_SCOPE_SUBTREE = 2

    Set objRoot = GetObject("LDAP://RootDSE")
    strDomainName = objRoot.Get("DefaultNamingContext")
    Set objRoot = Nothing

    strComputer = ""
    Dim fso
    Dim file

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile ("logged_user_list.txt", 2, True)
    Set objShell = CreateObject("WScript.Shell")

    Set objConnection = CreateObject("ADODB.Connection")
    Set objCommand = CreateObject("ADODB.Command")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Open "Active Directory Provider"

    Set objCommand.ActiveConnection = objConnection
    objCommand.CommandText = "Select Name, Location from 'LDAP://" & strDomainName & "'" _
    & "Where objectClass ='computer'"
    objCommand.Properties("Page Size") = 1000
    objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
    Set objRecordSet = objCommand.Execute

    & #39;****************************************************************************
    ******

    objRecordSet.MoveFirst

    Wscript.Echo "Processing information. This might take several minutes."

    Do Until objRecordSet.EOF
    strComputer = objRecordSet.Fields("Name").Value

    ' Проверяем доступность компьютера с помощью команды PING
    ' и анализа выходного потока

    Set objScriptExec = objShell.Exec("%comspec% /c ping.exe -n 1 " & strComputer)
    strPingResults = LCase(objScriptExec.StdOut.ReadAll)

    ' Если компьютер отвечает, подключаемся к его WMI

    If InStr(strPingResults, "ttl=") Then
    Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

    Set colComputer = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")

    ' Выводим список залогиненных пользователей в файл и на экран

    For Each objComputer in colComputer
    Wscript.Echo "Logged-on " &strComputer & " user: " & objComputer.UserName
    file.WriteLine("Logged-on " &strComputer & " user: " & objComputer.UserName)
    Next
    objRecordSet.MoveNext

    ' Если компьютер не отвечает - выводим сообщение и перемещаемся к следующему

    Else
    WScript.Echo(strComputer & ": Не отвечает...")
    objRecordSet.MoveNext
    End if
    Loop





    Этот скрипт просматривает системный журнал Безопасность и если обнаружит в нём запись об изменении настроек браузера, то уведомит об этом :

    On Error Resume Next
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:" _
    & "{"{impersonationLevel=impersonate,(Security)}!\\" & strComputer & _
    "\root\cimv2")
    Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("SELECT * FROM __InstanceCreationEvent WHERE TargetInstance ISA " _
    & "'Win32_NTLogEvent' AND TargetInstance.EventCode = '560' AND " _
    & "TargetInstance.Logfile = 'Security' GROUP WITHIN 2")
    Do
    Set objLatestEvent = colMonitoredEvents.NextEvent
    strAlertToSend = "Internet Explorer security settings have been " & _
    "changed."
    Wscript.Echo strAlertToSend
    Loop





    Скрипт ищет по всем контроллерам пользователей, которые не логинились уже более 90 дней и дизейблит их. После чего скидывает в файл их имена в форме Distinguished Name:

    Dim objRootDSE, strConfig, adoConnection, adoCommand, strQuery
    Dim adoRecordset, objDC
    Dim strDNSDomain, objShell, lngBiasKey, lngBias, k, arrstrDCs()
    Dim strDN, dtmDate, objDate, lngDate, objList, strUser
    Dim strBase, strFilter, strAttributes, lngHigh, lngLow
    Dim intUAC, objCurrentUser

    ' Использование объектов словаря чтоб потом узнать последние логоны пользователя.
    Set objList = CreateObject("Scripting.Dictionary")
    objList.CompareMode = vbTextCompare

    ' Получение местного времени с реестра.
    Set objShell = CreateObject("Wscript.Shell")
    lngBiasKey = objShell.RegRead("HKLM\System\CurrentControlSet\Control\" _
    & "TimeZoneInformation\ActiveTimeBias")
    If (UCase(TypeName(lngBiasKey)) = "LONG") Then
    lngBias = lngBiasKey
    ElseIf (UCase(TypeName(lngBiasKey)) = "VARIANT()") Then
    lngBias = 0
    For k = 0 To UBound(lngBiasKey)
    lngBias = lngBias + (lngBiasKey(k) * 256^k)
    Next
    End if

    ' Получение конфигурациы и доменов из объектов RootDSE.
    Set objRootDSE = GetObject("LDAP://RootDSE")
    strConfig = objRootDSE.Get("configurationNamingContext")
    strDNSDomain = objRootDSE.Get("defaultNamingContext")

    ' Использование ADO чтобы искать в Active Directory ObjectClass nTDSDSA.
    Set adoCommand = CreateObject("ADODB.Command")
    Set adoConnection = CreateObject("ADODB.Connection")
    adoConnection.Provider = "ADsDSOObject"
    adoConnection.Open "Active Directory Provider"
    adoCommand.ActiveConnection = adoConnection

    strBase = "<LDAP://" & strConfig & ">"
    strFilter = "(objectClass=nTDSDSA)"
    strAttributes = "AdsPath"
    strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"

    adoCommand.CommandText = strQuery
    adoCommand.Properties("Page Size") = 100
    adoCommand.Properties("Timeout") = 60
    adoCommand.Properties("Cache Results") = False

    Set adoRecordset = adoCommand.Execute


    k = 0
    Do Until adoRecordset.EOF
    Set objDC = _
    GetObject(GetObject(adoRecordset.Fields("AdsPath")).Parent)
    ReDim Preserve arrstrDCs(k)
    arrstrDCs(k) = objDC.DNSHostName
    k = k + 1
    adoRecordset.MoveNext
    Loop
    adoRecordset.Close

    ' Получение атрибута последнего логона для каждого пользователя в контроллерах домена.
    For k = 0 To Ubound(arrstrDCs)
    strBase = "<LDAP://" & arrstrDCs(k) & "/" & strDNSDomain & ">"
    strFilter = "(&(objectCategory=person)(objectClass=user))"
    strAttributes = "distinguishedName,lastLogon"
    strQuery = strBase & ";" & strFilter & ";" & strAttributes _
    & ";subtree"
    adoCommand.CommandText = strQuery
    On Error Resume Next
    Set adoRecordset = adoCommand.Execute
    If (Err.Number <> 0) Then
    On Error GoTo 0
    Wscript.Echo "Контроллер домена MGSM.RU не найден: " & arrstrDCs(k)
    Else
    On Error GoTo 0
    Do Until adoRecordset.EOF
    strDN = adoRecordset.Fields("distinguishedName")
    lngDate = adoRecordset.Fields("lastLogon")
    On Error Resume Next
    Set objDate = lngDate
    If (Err.Number <> 0) Then
    On Error GoTo 0
    dtmDate = #1/1/1601#
    Else
    On Error GoTo 0
    lngHigh = objDate.HighPart
    lngLow = objDate.LowPart
    If (lngLow < 0) Then
    lngHigh = lngHigh + 1
    End if
    If (lngHigh = 0) And (lngLow = 0 ) Then
    dtmDate = #1/1/1601#
    Else
    dtmDate = #1/1/1601# + (((lngHigh * (2 ^ 32)) _
    + lngLow)/600000000 - lngBias)/1440
    End if
    End if
    If (objList.Exists(strDN) = True) Then
    If (dtmDate > objList(strDN)) Then
    objList.Item(strDN) = dtmDate
    End if
    Else
    objList.Add strDN, dtmDate
    End if
    adoRecordset.MoveNext
    Loop
    adoRecordset.Close
    End if
    Next

    ' Создание логов
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objScriptFile = objFSO.OpenTextFile("c:\scripts\Account_lockout.vbs", _
    ForReading)
    Set objCommentFile = objFSO.OpenTextFile("c:\scripts\Lockedout_users.txt", _
    ForWriting, TRUE)

    'Сравнение дат

    dblCurrentdate = Cdbl(date)
    Const ADS_UF_ACCOUNTDISABLE = 2
    Const ForReading = 1
    Const ForWriting = 2

    For Each strUser In objList.Keys

    dblUserdate = Cdbl(objList.Item(strUser))

    If (dblCurrentdate - dblUserdate > 90) Then



    Set objCurrentUser = GetObject ("LDAP://" & strUser & "")
    intUAC = objCurrentUser.Get("userAccountControl")

    objCurrentUser.Put "userAccountControl", intUAC OR ADS_UF_ACCOUNTDISABLE
    objCurrentUser.SetInfo

    objCommentFile.Write strUser & VbCrLf

    ' Wscript.Echo strUser & " заблокирован"



    Else

    ' Wscript.Echo strUser & " недавно логинился"



    End if


    Next

    'Закрытие логов
    objScriptFile.Close
    objCommentFile.Close


    ' Очистка.
    adoConnection.Close
    Set objRootDSE = Nothing
    Set adoConnection = Nothing
    Set adoCommand = Nothing
    Set adoRecordset = Nothing
    Set objDC = Nothing
    Set objDate = Nothing
    Set objList = Nothing
    Set objShell = Nothing
    Set objCurrentUser = Nothing





    командный файл (closefl.bat ) закрывает все файлы, открытые пользователями в сети на вашем компьютере:
    if exist d:\files.txt del d:\files.txt
    net file > d:\files.txt
    for /f "skip=5 tokens=1" %%i in (d:\files.txt) do net file %%i /close
    del d:\files.txt
    
    





    Скрипт для уведомления пользователя об окончании действия учетки в домене за 10 дней: строке - dtmDaysToExpire > 10 ). Бросать в логон. В 5-й и 7-й строке подставить свои значения для домена и подразделения.

    ' Script name: WarnUserAboutAccountExpiration.vbs
    ' Created by Alex_GR - 26/05/2008

    'Указываем домен
    Const strDomainName="domen.com"
    'Указываем OU в AD, внутри которой мы будем искать
    Const strStartOU="Domain Users"
    strDomainDN="DC="&Replace(strDomainName,".",",DC=")

    On Error Resume Next
    'Option Explicit
    Dim strUserName, oNetwork, aConnection, aCommand, aResult, strDN, dtmAccountExpiration, dtmDaysToExpire, oShell
    Set oNetwork = CreateObject("Wscript.network")
    Set oShell = CreateObject("Wscript.shell")
    strUserName = oNetwork.UserName
    Set aConnection = CreateObject("ADODB.Connection")
    Set aCommand = CreateObject("ADODB.Command")
    aConnection.Provider = "ADsDSOObject"
    aConnection.Open
    aCommand.ActiveConnection = aConnection
    aCommand.CommandText="<LDAP://OU="&strStartOU&","&strDomainDN&">;(&(objectCategory=User)(samAccountName=" & strUserName & "));distinguishedName;subTree"
    Set aResult = aCommand.Execute()
    strDN = aResult.Fields("distinguishedName")
    Set objUser = GetObject("LDAP://" & strDN)
    dtmAccountExpiration = objUser.AccountExpirationDate
    dtmDaysToExpire = DateDiff("d", Now, dtmAccountExpiration)
    If Err.Number = -2147467259 Or dtmAccountExpiration = "1/1/1970" Or dtmAccountExpiration = "01/01/1601 03:00:00" Or dtmAccountExpiration = "01.01.1601 03:00:00" Or dtmAccountExpiration = "1.1.1970" Or dtmDaysToExpire > 10 Then
    ' Можно выводить другое сообщение, если найдено соответствие условию
    ' MsgBox "Всe good "
    Else
    oShell.Popup "До окончания испытательного срока осталось " & dtmDaysToExpire & " дней!" & vbCrLf & _
    "Учётная запись действительна до " & dtmAccountExpiration & vbCrLf & _
    "Просьба об этом уведомить Вашего руководителя.", 60, "Уведомление от ИТ Департамента", 48+0
    End if





    Скрипт для поиска в активном каталоге пользователей с ограниченым сроком действия учётки и экспорта в файл: В 5-й и 7-й строке подставить свои значения для домена и подразделения.

    ' Script name: UserAccountExpirationDate.vbs
    ' Created by Alex_GR - 12/05/2008

    'Указываем домен
    Const strDomainName="domen.com"
    'Указываем OU в AD, внутри которой мы будем искать
    Const strStartOU="Domain Users"
    strDomainDN="DC="&Replace(strDomainName,".",",DC=")

    ---------------------Получение данных--------------------
    Set objConnection = CreateObject("ADODB.Connection")
    objConnection.Open "Provider=ADsDSOObject;"
    Set objCommand = CreateObject("ADODB.Command")
    objCommand.ActiveConnection = objConnection
    objCommand.CommandText = "<LDAP://OU="&strStartOU&","&strDomainDN&">;(&(objectCategory=person)(objectClass=user));ADsPath;subtree"
    objCommand.Properties("Page Size")=9000

    Set objRecordSet = objCommand.Execute

    Const ForAppending = 2
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objTextFile = objFSO.OpenTextFile ("c:\UserAccountExpirationDate.txt", ForAppending, True)

    '------Индексирование --------
    While Not objRecordset.EOF
    strADsPath = objRecordset.Fields("ADsPath")
    Set objUser = GetObject(strADsPath)

    dtmAccountExpiration = objUser.AccountExpirationDate

    If err.number = -2147467259 Or dtmAccountExpiration = "01/01/1970" Or dtmAccountExpiration = "01/01/1601 03:00:00" Or dtmAccountExpiration = "01.01.1601 03:00:00" Or dtmAccountExpiration = "01.01.1970" Then
    'Вывод сообщением
    'WScript.echo ""

    'запись в файл пустого значения
    objTextFile.Write ""
    objRecordset.MoveNext

    Else
    'Вывод сообщением
    ' WScript.echo objUser.displayName & " - учётка действительна до: " & objUser.AccountExpirationDate

    'Запись в файл
    objTextFile.WriteLine objUser.displayName & " - учётка действительна до: " & objUser.AccountExpirationDate
    objRecordset.MoveNext
    End if

    Wend
    objConnection.Close
    WScript.echo "Экспорт закончен, файл создан - C:\UserAccountExpirationDate.txt"





    Скрипт який перевіряеє нових юзерів і відсилає ім лист з вказаним текстом: (переверяє з тією ж періодичністю з якою виконуеться скрипт тобто та яка вказана в Scheduled Tasks)

    'Created by Mike Ruman 8/13/05
    'Sends an email to accounts created today.

    Dim StrDate, CurrentUTC

    'Create the current date and time stamp for query for day before last
    CurrentUTC = DatePart("yyyy", Date)
    'now add Month in mm if only M add leading 0
    if DatePart("m" , Now) < 10 then
    CurrentUTC = CurrentUTC & 0 & DatePart("m" , Now)
    else
    CurrentUTC = CurrentUTC & DatePart("m" , Now)
    end if
    'now add Day in dd if only d add leading 0
    if DatePart("d" , Now) < 10 then
    'OPTIONAL - FOR MANY DAYS, replace line below with CurrentUTC = CurrentUTC & 0 & DatePart("d" , Now - X) where X = # of days

    CurrentUTC = CurrentUTC & 0 & DatePart("d" , Now)
    else
    'OPTIONAL - FOR MANY DAYS, replace line below with CurrentUTC = CurrentUTC & DatePart("d" , Now - X) where X = # of days
    CurrentUTC = CurrentUTC & DatePart("d" , Now)
    end if
    ' Tag hour, minute, second on
    strDate = CurrentUTC&"000001.0Z"

    'Create AD Connection
    Set oConnection1 = CreateObject("ADODB.Connection")
    Set oCommand1 = CreateObject("ADODB.Command")
    oConnection1.Provider = "ADsDSOObject" ' This is the ADSI OLE-DB provider name
    oConnection1.Open "Active Directory Provider"
    ' Create a command object for this connection.
    Set oCommand1.ActiveConnection = oConnection1
    'Set Query definition
    ' тут задаем доменные параметры берем из AD
    oCommand1.CommandText = "select mail from 'LDAP://DC=it, DC=local' WHERE objectCategory='Person' AND objectClass='user'AND msExchHideFromAddressLists<>'True' AND whenCreated>='" & strDate & "'"

    oCommand1.Properties("Page Size") = 30000
    ' Execute the query.
    Set rs = oCommand1.Execute


    rs.movefirst
    'Create the loop of results
    Do Until rs.EOF = True


    'Create Email
    ' настройки письма для пользователя
    Set objEmail = CreateObject("CDO.Message")
    objEmail.From = "Admin@mycantora.ua"
    objEmail.To = rs.Fields("mail")
    'Optional BCC field
    'objEmail.BCC = "Admin@mycantora.ua"
    objMessage.BodyPart.CharSet = "windows-1251"
    objEmail.Subject = "A welcome message from Exchange"
    objEmail.Textbody = "Добро пожаловать в ........."
    'Optional Add an attachment
    'objEmail.AddAttachment "C:\new_hire_audio_message.wav"
    objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
    "ExchangeServer" 'Replace ExchangeServer with server IP or name
    objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    objEmail.Configuration.Fields.Update
    'Optional - Read the message before it's sent
    'MsgBox objEmail.GetStream.ReadText
    objEmail.Send
    rs.movenext
    Loop

    'Close AD Connection
    oConnection1.close





    Этот скрипт vbs, написанный мной спонтанно, позволяет устанавливать или сбрасывать флажок «разрешить удалённый доступ к этому компьютеру» на вкладке удалённые сеансы в свойствах системы! Теперь вы сможете подключаться к удалённому рабочему столу любой машины в вашей сети…: Переписать скрипт на любой язык программирования, включая мой любимый С++ не составит труда даже для самых юных кодеров! VBS выбран мной только из соображений лени, если так можно выразиться (под руками был генератор скриптов именно vbs) правда править его ручками пришлось всё равно!

    1. подставьте нужные значения
    strComputer = "ИмяУдалённогоКомпьютера"
    strDomain = "ИмяДомена"
    2. подставьте имя машины на которой запускаете скрипт
    ServerName='ИмяКомпьютера'
    3. параметр = 1 установит флажок параметр = 0 сбросит его
    objInParam.Properties_.Item("AllowTSConnections") = 1

    Запустить скрипт легко по контекстному меню смотрите рисунки.

    PS Проверено на 32 битных и 64 битных системах (WindowsServer2003, WindowsXP)

    strComputer = "ИмяУдалённогоКомпьютера"
    strDomain = "ИмяДомена"
    Wscript.StdOut.Write "Please enter your user name:"
    strUser = Wscript.StdIn.ReadLine
    Set objPassword = CreateObject("ScriptPW.Password")
    Wscript.StdOut.Write "Please enter your password:"
    strPassword = objPassword.GetPassword()
    Wscript.Echo

    Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
    Set objWMIService = objSWbemLocator.ConnectServer(strComputer, _
    "root\CIMV2", _
    strUser, _
    strPassword, _
    "MS_409", _
    "ntlmdomain:" + strDomain)
    ' Obtain an instance of the the class
    ' using a key property value.
    Set objShare = objWMIService.Get("Win32_TerminalServiceSetting.ServerName='ИмяКомпьютера'")

    ' Obtain an InParameters object specific
    ' to the method.
    Set objInParam = objShare.Methods_("SetAllowTSConnections"). _
    inParameters.SpawnInstance_()


    ' Add the input parameters.
    objInParam.Properties_.Item("AllowTSConnections") = 1

    ' Execute the method and obtain the return status.
    ' The OutParameters object in objOutParams
    ' is created by the provider.
    Set objOutParams = objWMIService.ExecMethod("Win32_TerminalServiceSetting.ServerName='ИмяКомпьютера'", "SetAllowTSConnections", objInParam)

    ' List OutParams
    Wscript.Echo "Out Parameters: "
    Wscript.echo "ReturnValue: " & objOutParams.ReturnValue






    выключить--включить адаптер:

    strNetConn = "Сетевые подключения" ' Network Connections для англ. версии ОС
    strConn = "Подключение по локальной сети" ' имя или часть имени подключения
    strEnable = "&Включить" ' En&able для англ. версии ОС
    strDisable = "&Отключить" ' Disa&ble для англ. версии ОС

    Set objShell = CreateObject("Shell.Application")
    Set objCP = objShell.Namespace(3) ' Панель управления
    For Each elem in objCP.Items
    If elem.Name = strNetConn Then
    ' получение папки "Сетевые подключения"
    Set colNetwork = elem.GetFolder
    Exit For
    End if
    Next

    Set Conn = Nothing
    For Each clsConn in colNetwork.Items
    If Instr(LCase(clsConn.name), LCase(strConn)) Then
    ' получение указанного подключения
    Set Conn = clsConn
    Exit For
    End if
    Next
    If Conn Is Nothing Then
    WScript.Echo "Network Connection not found"
    WScript.Quit
    End if

    bEnabled = True
    Set objEnable = Nothing
    Set objDisable = Nothing
    For Each clsVerb in Conn.verbs
    ' если доступен глагол "Enable", подключение отключено
    If clsVerb.Name = strEnable Then
    Set objEnable = clsVerb
    bEnabled = False
    End if
    ' если доступен глагол "Disable", подключение подключено
    If clsVerb.name = strDisable Then
    Set objDisable = clsVerb
    End if
    Next

    If bEnabled Then
    objDisable.DoIt
    strStatus = "disabled."
    Else
    objEnable.DoIt
    strStatus = "enabled."
    End if
    WScript.Sleep 1000

    WScript.Echo Conn.Name & " " & strStatus





    Скрипт для перезапуска ADSL мопеда D-link DSL-2640U: "telnet.exe 192.168.1.1" - или другой IP на котором сидит модем Будет работать и на других моделях но возможно придется посмотреть в телнете что писать в oShell.SendKeys "??" & chr(13) после того как залогинишся
     rem Заходим на мопед 
    Set oShell = WScript.CreateObject("WScript.Shell")
    oShell.Run "telnet.exe 192.168.1.1"
    WScript.Sleep 1000
    oShell.SendKeys "Имя" & chr(13)
    WScript.Sleep 1000
    oShell.SendKeys "Пароль" & chr(13)
    rem Перезапускаем
    WScript.Sleep 1000
    oShell.SendKeys "13" & chr(13)
    WScript.Sleep 1000
    oShell.SendKeys "1" & chr(13)





    скрипт для создания учеток пользователей из списка. (txt, xls): где файл users.csv должен содержать информацию о юзерах в следующем формате.
    Import-CSV users.csv | ForEach-Object { New-QADUser -ParentContainer scorpio.local/users -Name ($_.Familia + ', ' + $_.Imya) -samAccountName ($_.Imya[0] + $_.Familia) -Department $_.Department -Title $_.Title}
    
    





    Перезапуск служб apache , mysql , cron , sendmail :
    #!/bin/bash
    echo "Services restart: ";
    
    cd /etc/rc.d/init.d/
    ./httpd restart
    ./mysqld restart
    ./crond restart
    ./sendmail restart