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
  • Checking for changes in AD parameters and sending to e-mail or Sharepoint list
  • Script for removing terminal licenses on clients, every 30 days
  • The anti-mail.ru agent scripts
  • The script does a backup of the system and uploads it to the ftp
  • blocks / unblocks users in AD, taking from the specified file a list of their name
  • copying a file into user roaming profiles
  • The script searches for all controllers of users who have not logged in for more than 90 days and disable them
  • The batch file (closefl.bat) closes all files opened by users on the network on your computer
  • Script for notifying the user about the expiration of accounting in the domain for 10 days
  • Script for searching the users directory with a limited validity period of the account and exporting to a file
  • Script yakii perevіryaєe novyh yuzerіv i vіsilаіі ім sheet з in the text
  • Set or clear the checkbox "Allow remote access to this computer"
  • turn off - turn on the adapter
  • Inventory all machines in the domain
  • Determining When an Account Expires (Returns the Expiration date for a user account)
  • Determining When a User Account Expires
  • Recursively assigns to all users of the domain the attribute "User must change password on next logon"
  • Obtaining the SID (s) of a computer from AD
  • Search for accounts in ActiveDirectory with expired passwords
  • Interrogates computers, on the subject, which user is logged in at the moment
  • Monitors the system log and notifies you about changing the browser settings
  • Script for restarting the ADSL moped D-link DSL-2640U
  • A script to create user accounts from the list. (txt, xls)
  • Restart apache, mysql, cron, sendmail services


  • Open the notepad, copy the code there and save the document with the .vbs extension. Next, if the network without domains copy this file into startup for each PC. If the network is a domain, then you create a group policy (in AD), where you insert this file into the Startup parameters. Then, when you connect or restart the account, the script will run






    To connect a network drive:
     Set WshNetwork = CreateObject ("WScript.Network") 'Create an object of type Network Set Drives = WshNetwork.EnumNetworkDrives c = 0' Time-tested for at least one network drive!  i = 0 While i <= Drives.Count-1 'Check for network wildcards 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 is not a single mounted drive "'MsgBox" Attempting to mount a network drive "' Set WshNetwork = CreateObject (" WScript.Network ") WshNetwork.MapNetworkDrive" Z: "," \ \ Servername \ folder name "End if 





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





    Checking the changes in the parameters in AD and sending the notification to e-mail or to the Sharepoint list:


    / * ================================================ ========
    '
    'Script Information: Send a message to the administrator
    'when you change the data in AD, you can send a message
    'to e-mail or create a task in MOSS 2007
    '
    'Author: Korotenko Vladimir SDC 2008 Voronezh
    'Created by: 15.04.2008 - 11:01:47
    'Original path: untitled.vbs
    'Description: Create a domain schema dump and compare
    'with the previous copy to receive the changes and the subsequent
    'notification
    '
    '================================================= =======
    * /




    // Section of script settings
    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; // the port of the mail server
    MailSubject = "Make changes to the organizational chart"; // the title of the letter message
    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 for dumping their AD data
    WinDiff = "c: \\ temp \\ windiff.exe"; // Program for comparison 2
    DumpFile = "schema.ldf"; // Name of the file to save
    DumpFileOld = "schemaOld.ldf"; // Name 2 files to compare
    WorkingFolder = "c: \\ temp \\"; // working folder for temporary files

    DiffFile = "diff.log"; // Service file for comparison results
    DiffMessage = "1 files listed"; // the line we are looking for if there are no files

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

    // End of the settings section

    / ************************************************* ********************
    Code to change only in case of deep understanding for what do
    and most importantly HOW you do !!!!!!!!!
    ************************************************** ******************** /

    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 a difference of 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 if 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 rows 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 ();
    }



    // Sending a message to an 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 licenses on clients, every 30 days:

    'Deletes, if necessary, the registry key in which temporary licenses are stored, if 30 days have elapsed.
    Option Explicit
    Dim iCount, dDat, dReadDat, strPath, strRegKey 'declaration of variables
    Dim fso, fLogFile, wshSysEnv, wshShell 'declaration of objects

    dDat = date 'get the current date
    err.clear 'yf just in case we clean the error stack

    on error resume next 'After this error message is not displayed

    'Create the Shell object
    Set wshShell = WScript.CreateObject ("WScript.Shell")
    'Create an Environment object that contains the required system variable
    Set wshSysEnv = WshShell.Environment ("PROCESS")
    'We pull out the system variable (the path to the Windows folder) and put it in a string variable for later use
    strPath = wshSysEnv ("WINDIR")

    'Create an access object to the file system and an object to access the required file for reading
    Set fso = CreateObject ("Scripting.FileSystemObject")
    set fLogFile = fso.OpenTextFile (strPath & "\ LiDelDat.alx", 1, false)

    'The main condition for removing or uninstalling the registry branch
    If err.number <> 0 then
    'Performing the procedure to delete the registry branch
    Call DelLicense

    'Enter the last date for deleting the license in the log file, erasing the entry in it
    Call WriteToLog
    Else
    'Read from the file and compare the date the license was last deleted with the current date
    dReadDat = CDate (fLogFile.ReadLine ())

    'Must be (dDat - dReadDat)
    If (dDat - dReadDat)> 29 Then
    'Performing the procedure to delete the registry branch
    Call DelLicense

    'Enter the last date for deleting the license in the log file, erasing the entry in it
    Call WriteToLog
    End If
    End If

    'We destroy all unnecessary more objects
    Set WshShell = Nothing
    Set wshSysEnv = Nothing
    Set fso = Nothing

    '************************************************* ***********
    'Procedures
    '************************************************* ***********
    'License removal procedure
    Sub DelLicense ()
    'Remove the license-plug-in one at a time
    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

    'Delete the subkeys of the main partition
    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 partition
    WshShell.RegDelete ("HKLM \ SOFTWARE \ Microsoft \ MSLicensing \")
    if err.number <> 0 then err.clear

    End Sub

    'The procedure for recording the date the license was last deleted to a file
    Sub WriteToLog ()
    err.clear

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

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

    set fLogFile = nothing 'destroy the 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 sirs system administrators, I am informing you that the enemy mail.ru agent is destroyed from" + WshSysEnv ("userprofile")
    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 does a backup of the system and pours it into 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, taking a list of their name from the specified 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 domain
    Const strDomainName = "<domain name eg domain.com>"
    'We specify OU in AD, inside which we will look for
    Const strStartOU = "Domain Users"
    strDomainDN = "DC =" & Replace (strDomainName, ".", ", DC =")

    '--------------------- Getting 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

    'The path to the file in which the list of people's names is stored. Account records of which you need to open / close
    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 an array
    inputDataFromFiried = Split (objInputFileFromKardy.ReadAll, vbNewline)
    'Reset the results lists
    UserDisables = ""
    UserUpdated = ""
    UserNoFound = ""
    UserDuplicated = ""
    ii = 0


    For each strFULL In inputDataFromFiried
    if Len (strFULL)> 5 then
    'reset the counter found matching
    e = 0
    '1st field: select from the line
    strFIO = Left (strFULL, InStr (strFULL, ";") - 1)
    'We break apart by 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, ""))))
    'We collect by parts Name
    strFIO = Familia & "" & Imya & "" & Otchestvo

    index = maxindex
    While index> 1

    'We split by parts the name in AD

    AdFamilia = ""
    AdImya = ""
    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


    'We collect by parts Name
    AdstrFIO = AdFamilia & "" & AdImya & "" & AdOtchestvo
    AdstrFIO1 = 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
    'we 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 the mail is sent>"
    objMessage.To = "<e-mail to whom the mail is sent>"
    objMessage.Subject = "Subject of the letter"

    '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") = "<smtp server 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 TRUE is the user's disable, 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 designed to copy a file into user-defined roaming profiles:

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

    DeepCount ++;
    //WScript.Echo(DeepCount);
    if (DeepCount <DeepLimit)
    {
    fsoPolFldr = FSO.GetFolder (PolFldr);
    // Get the collection of subdirectories of the system policy catalog
    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
    }
    // ************************************************ ********************************

    //
    //


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

    // Stopper
    // ************************************************ ********************************

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

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




    // ************************************************ ********************************
    *
    // Declare Global Variables
    // ************************************************ ********************************
    *
    var FSO, // FileSystemObject
    Path2Scripts, // The path to the file to be distributed (it is assumed that the files are in the same folder as this file)
    DeepCount, // Depth of recursion counter
    DeepLimit, // Limiting the depth of recursion
    PolF; // Root, from which the search and distribution of files on the underlying folders begins
    // ************************************************ ********************************
    *
    PolF = "\\\\ DC \\ UserFolders \\ OZI"; ////
    // Create the FileSystemObject;
    FSO = WScript.CreateObject ("Scripting.FileSystemObject");
    DeepCount = 0;
    Path2Scripts = FSO.GetParentFolderName (FSO.GetFile (WScript.ScriptFullName));
    // Limit the depth of recursive calls
    DeepLimit = 4;
    LoopSubFolders (PolF, DeepCount);





    Inventory 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) + "Collection date:" & invdate & "<table>" + chr (10)
    compname = ""
    'on error resume 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 + "CPU" + 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 10)
    temp = temp + "</ tr>" + chr (10)
    case 4
    temp = temp + "<tr>" + chr (10) + "<td>"
    temp = temp + "video controller" + "</ td>" + chr (10) + "<td>" + objitem.caption + chr (10) + "</ td>"
    temp = temp + "</ tr>" + chr (10)
    case 5
    if objitem.adaptertypeid = 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 a 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 When an Account Expires (Returns 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 a User Account Expires (Reports the date that the MyerKen 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 establishes the attribute "User must change password on next logon" to all users of the domain: PS For correct operation, it is necessary to define the domain name from the LDAP point of view in the variable strMyDomain. replace all points with "DC =". Thus, the domain argo.com turns into DC = argo, DC = com, into the variable strMyOU, it is necessary to put the name Organization Unit, whose users 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 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