Scripts pour les administrateurs système, les scripts utiles pour Win2003



  • Pour connecter le lecteur réseau
  • Pour connecter l'imprimante
  • Vérifiez les paramètres de l' évolution de la MA et l' envoi d' e-mail ou dans une liste de Sharepoint
  • Script pour supprimer la licence pour les clients de terminaux, tous les 30 jours
  • Script pour lutter contre mail.ru agent
  • Le script rend le système de sauvegarde et verse sur le ftp
  • bloquer / débloquer les utilisateurs dans AD, en tenant à partir d' une liste spécifique de nom de fichier
  • Copiez le fichier sur les profils utilisateur d'itinérance
  • Le script recherche tous les contrôleurs utilisateurs qui ne se connecte pas est déjà plus de 90 jours et leur dizeyblit
  • fichier batch (closefl.bat) ferme tous les fichiers ouverts par les utilisateurs sur le réseau sur votre ordinateur
  • Le script pour la notification de l' utilisateur de la fin de domaine uchetki pendant 10 jours
  • Le script pour rechercher le répertoire de l' utilisateur avec une durée de validité limitée uchёtki et l' exportation vers un fichier
  • Script Yaky perevіryaeє novih i yuzerіv vіdsilaє IM texte s liste vkazanim
  • Définit ou réinitialise la case à cocher "Autoriser l' accès à distance à cet ordinateur"
  • Disabled - Adapter Enabled
  • Iventarizatsiya toutes les machines dans le domaine
  • Déterminer quand un compte Expire (Retourne la date d'expiration pour un compte d'utilisateur)
  • Déterminer quand un compte d'utilisateur Expire
  • " L' utilisateur doit changer le mot de passe sur la prochaine ouverture de session " installer récursive tous les utilisateurs de domaine attribuent
  • Préparation SID (a) de l'ordinateur AD
  • Recherche dans les comptes ActiveDirectory avec mots de passe expirés
  • Sondages ordinateurs pour lesquels l' utilisateur est connecté en ce moment
  • Moniteurs fichier journal et informe les modifier les paramètres du navigateur
  • Script pour redémarrer l'ADSL cyclomoteur D-link DSL-2640U
  • uchetok script pour créer des utilisateurs dans la liste. (Txt, xls)
  • Redémarrez le service apache, mysql, cron, sendmail


  • portable Otkryvaesh, et que vous copiez le code pour sohranyaesh document avec l'extension .vbs. Ensuite, si vous copiez sans un domaine de réseau que j'ai trouvé dans chaque démarrage du PC. Si le domaine de réseau, les politiques grupovogo sozdaesh (AD), où les paramètres vstavlyaesh fichier de démarrage. Ensuite, le script sera exécuté lorsque vous vous connectez ou redémarrez compte






    Pour connecter le lecteur réseau:
     Set WshNetwork = CreateObject ( "WScript.Network") "Créer tapez l'objet Set lecteurs réseau = WshNetwork.EnumNetworkDrives c = 0 'de la variable est vérifiée pour au moins un lecteur réseau!  i = 0 Alors que i <= Drives.Count-1 'Vérifiez réseau Dikov c = 1' MsgBox "Avez-vous un lecteur réseau" & Drives.Item (i) et "-" & Drives.Item (i + 1) i = i + 2 Wend si c = 0 puis 'MsgBox "Il n'y a pas un lecteur mappé"' MsgBox "une tentative de mapper un lecteur réseau" 'Set WshNetwork = CreateObject ( "WScript.Network") WshNetwork.MapNetworkDrive "Z:", "\ \ servername \ nom du dossier "Fin de si 





    Pour connecter l'imprimante:
     Set WshNetwork = WScript.CreateObject ( "WScript.Network")
     WshNetwork.AddWindowsPrinterConnection "\\ imyaprintservera \ nom de l'imprimante"
    
    





    Vérifiez les paramètres de l' évolution des AD et l' envoi de notifications par e-mail ou dans une liste de Sharepoint:


    / * ================================================ ========
    '
    'Script Information: Envoi de messages à l'administrateur
    «Quand les données dans AD peuvent envoyer des messages
    'E-mail ou de créer une tâche dans MOSS 2007
    '
    'Auteur: Vladimir Korotenko DDC 2008 Voronezh
    «Initialement créé: 15.04.2008 - 11:01:47
    «Chemin d'origine: untitled.vbs
    'Description: Création vidage schéma de domaine et comparer
    'D'une copie précédente pour les modifications, puis
    notification '
    '
    '================================================= =======
    * /




    // Section Paramètres de script
    var SMTPHost, SMTPPORT, mailSubject, MailTo, MailFrom, TextBody;
    var DumpCmdLine, WinDiff, DumpFile, DumpFileOld, WorkingFolder;
    var DiffFile, DiffMessage;
    var SpListGuid, SpHost, UseSp;

    SMTPHost = "comp1"; serveur // E-mail pour envoyer des messages
    SMTPPORT = 25; // Port du serveur de messagerie
    MailSubject = "Apporter des modifications à l'organigramme"; // messages d'en-tête d'écriture
    MailTo = "[email protected]"; // Adresse du destinataire
    MailFrom = "[email protected]"; // De Adresse
    DumpCmdLine = "c: \\ windows \\ system32 \\ ldifde.exe"; // Ligne de commande pour vider leurs données AD
    WinDiff = "c: \\ temp \\ windiff.exe"; // Programme pour Comparer 2
    DumpFile = "schema.ldf"; // Nom 1 fichier pour enregistrer
    DumpFileOld = "schemaOld.ldf"; // Nom 2 fichiers de comparaison
    WorkingFolder = "c: \\ temp \\"; // Dossier de travail pour les fichiers temporaires

    DiffFile = "diff.log"; // Appel de fichier pour comparer les résultats
    DiffMessage = "1 fichiers répertoriés"; // Ligne que nous examinons les fichiers de lichii

    SpListGuid = "{3D9B5EFB-C0C5-434C-B1DA-61FEA6E9D63B}";
    SpHost = "http: // portal4";
    UseSp = true; // Envoyer des messages à la liste de Share Point

    // réglages de la section Fin

    / ************************************************* ********************
    Le seul changement dans le cas d'une compréhension profonde de ce code faisant
    et surtout comment faire !!!!!!!!!
    ************************************************** ******************** /

    fichier var, wsh;
    // Création d'un objet pour

    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);




    // Vérifiez la différence de 2 fichiers
    CheckChanges de fonction (pathFrom, pathto)
    {
    cmd var;
    // 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 ++)
    {
    // Vérifiez si les fichiers sont différents, donc si vous envoyez un message

    if (arr [i] .indexOf (DiffMessage)> - 1)
    {
    var d = new Date ();
    TextBody = "changements détectés dans le temps de circuit de comparaison." + D.toString ();
    SendMessage ();
    }
    }
    }



    // Retirer la chaîne à partir des attributs qui changent fréquemment
    fonction TrimUnused (nom)
    {
    var ForReading = 1;
    var ForWriting = 2;
    var objFSO, objFile;


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

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

    objFile = objFSo.OpenTextFile (nom, ForWriting);

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



    // Envoyer un e-mail à tous les paramètres doivent être spécifiés dans les variables globales de la section

    fonction SendMessage () {

    if (UseSp)
    {
    NewMessage (SpListGuid, SpHost, TextBody);
    retour;
    }
    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 ();

    }

    // Création d'un nouveau message dans une liste de Sharepoint
    fonction NewMessage (liste, hostName, message)
    {
    var web, req, lot;
    web = new ActiveXObject ( "MSXML2.XMLHTTP.3.0");

    lot = "<Batch ListVersion = '0'> <Méthode ID = '1' Cmd = 'Nouveau'> <Nom du champ = 'Le titre'>" + + message "</ Champ> </ Méthode> </ Batch>" ;

    var req = "<? xml version = '1.0' encoding = 'utf-8' ??> <soap: Envelope xmlns: 'http: //www.w3.org/2001/XMLSchema-instance' xsi = xmlns: xsd = xmlns 'http://www.w3.org/2001/XMLSchema~~number=plural': savon = 'http: //schemas.xmlsoap.org/soap/envelope /> <soap: Body> <http UpdateListItems xmlns =': // schemas.microsoft.com/sharepoint/soap / '> ";
    req + = "<listName>" + liste + "</ listName>";
    req + = "<mises à jour>" + lot + "</ mises à jour> </ 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);

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

    }





    Script pour supprimer la licence de terminaux sur les clients tous les 30 jours:

    «Enlève si la clé de Registre nécessaire, qui stocke licence temporaire si 30 jours se sont écoulés.
    Option Explicit
    Dim iCount, DDAT, dReadDat, strPath, déclaration strRegKey 'des variables
    Dim fso, fLogFile, wshSysEnv, installations classées WshShell '

    DDAT = date 'obtenir la date actuelle
    Err.Clear 'yf toute propre erreur de pile de cas

    On Error Resume Next 'est pas affiché après ce message d'erreur

    'Créer objet Shell
    Set WshShell = WScript.CreateObject ( "WScript.Shell")
    «Créer un objet Environnement, qui contient la variable système requise
    Set wshSysEnv = WshShell.Environment ( "PROCESS")
    «Nous prenons la variable système (le chemin du dossier vindovskoy) et le placer dans une variable de chaîne pour une utilisation ultérieure
    strPath = wshSysEnv ( "WINDIR")

    «Créer un accès au système de fichier objet et l'accès de l'objet pour le fichier à lire
    Set fso = CreateObject ( "Scripting.FileSystemObject")
    définir fLogFile = fso.OpenTextFile (strPath & "\ LiDelDat.alx", 1, false)

    "La principale condition pour le retrait ou non retiré branche de registre
    Si Err.Number <> 0 alors
    «procédures de branche de registre à distance en cours
    Appelez DelLicense

    «Saisie de la dernière date de la suppression de la licence pour le fichier journal, en écrasant l'entrée existante dans ce
    Appelez WriteToLog
    autre
    «Je lis à partir du fichier et compare la date du dernier retrait d'une licence avec la date actuelle
    dReadDat = CDate (fLogFile.ReadLine ())

    «Il doit y avoir (DDAT - dReadDat)
    Si (DDAT - dReadDat)> 29 Ensuite,
    «procédures de branche de registre à distance en cours
    Appelez DelLicense

    «Saisie de la dernière date de la suppression de la licence pour le fichier journal, en écrasant l'entrée existante dans ce
    Appelez WriteToLog
    End If
    End If

    «Détruisez tous les objets inutiles plus
    Réglez WshShell = Nothing
    Réglez wshSysEnv = Nothing
    Set fso = Nothing

    '************************************************* ***********
    «procédures
    '************************************************* ***********
    «La procédure de retrait de la licence
    Sous DelLicense ()
    'Retirez le bouchon-licence pour un
    On Error Resume Next
    Err.Clear

    pour iCount = 0 à 9
    strRegKey = "HKLM \ SOFTWARE \ Microsoft \ MSLicensing \ Store \ License00" & iCount & "\"
    WshShell.RegDelete (strRegKey)

    Si Err.Number <> 0 alors
    Err.Clear
    End If
    suivant

    'Retirez le bouchon de la section principale
    WshShell.RegDelete ( "HKLM \ SOFTWARE \ Microsoft \ MSLicensing \ Store \")
    si Err.Number <> 0 alors Err.Clear

    WshShell.RegDelete ( "HKLM \ SOFTWARE \ Microsoft \ MSLicensing \ HardwareID \")
    si Err.Number <> 0 alors Err.Clear

    "Supprimer la partition primaire
    WshShell.RegDelete ( "HKLM \ SOFTWARE \ Microsoft \ MSLicensing \")
    si Err.Number <> 0 alors Err.Clear

    End Sub

    «La procédure d'enregistrement de la date de la dernière suppression du fichier de licence
    Sous WriteToLog ()
    Err.Clear

    «Créer un accès aux objets dans le fichier désiré sur l'enregistrement et écraser les entrées précédentes
    définir fLogFile = fso.OpenTextFile (strPath & "\ LiDelDat.alx", 2, true)

    «Écrivez au registre date de nettoyage de fichiers
    fLogFile.Write (Date)

    définir fLogFile = rien "détruire l'objet
    End Sub





    Script pour lutter contre 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"


    Si objFSO.FileExists (agentFile) Ensuite,

    objFSO.DeleteFile (agentFile), DeleteReadOnly


    si Err.Number = 0 alors
    Set objEmail = CreateObject ( "CDO.Message")

    objEmail.From = "[email protected]"
    objEmail.To = "[email protected]"
    objEmail.Subject = "Mail.ru-agent"
    objEmail.Textbody = "Cher Monsieur, les administrateurs système, vous informe qu'un ennemi est détruit agent mail.ru de" + 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") = _
    "Serveur de messagerie Ip"
    objEmail.Configuration.Fields.Item _
    ( "Http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    objEmail.Configuration.Fields.Update
    objEmail.Send

    fin si

    fin si





    Le script rend le système de sauvegarde et verse sur le ftp:

    strComputer = "."
    Set WshShell = WScript.CreateObject ( "WScript.Shell")
    strCommand = "C: \ WINDOWS \ system32 \ ntbackup.exe @C de sauvegarde: \ cmd \ Back-UP-Drive-C.bks / a / v: no / r: non / rs: no / hc: off / m normale / 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")

    Pour chaque objItem dans colItems
    strCommand = "C: \ Arc \ 7z.exe un D: \ Sauvegarde \ Backup-dc-srv-01-DayOf-Semaine -" & 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 "
    suivant
    WshShell.Run strCommand, 1, true
    strCommand = "ftp -s: C: \ CMD \ ctp-command.txt"
    WshShell.Run strCommand, 1, true





    Le bloc de script / débloquer les utilisateurs dans l'AD, en les prenant à partir d' une liste spécifique de nom de fichier, et aviser l'administrateur par courrier des résultats:

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

    'Indiquez le nom de domaine
    Const strDomainName = "<nom de domaine par exemple domain.com>"
    'Spécifier l'unité d'organisation dans AD, au sein de laquelle nous chercherons
    Const strStartOU = "Utilisateurs du domaine"
    strDomainDN = "DC =" & Replace (strDomainName, ".", "DC =")

    '--------------------- -------------------- Obtenir des données
    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 ( "Taille de la page") = 4000

    Set objRecordSet = objCommand.Execute


    'Indexation -------- ------
    index = 0
    Bien que non 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

    «Chemin du fichier qui stocke la liste des noms des personnes dont les comptes ont besoin pour ouvrir / fermer
    strFileOfFiried = "d: \ file_of_firied.txt"

    Set objFileSystem = CreateObject ( "Scripting.FileSystemObject")
    Set objInputFileFromKardy = objFileSystem.OpenTextFile (strFileOfFiried, OPEN_FILE_FOR_READING)
    'Échappements contenu du fichier dans un tableau
    inputDataFromFiried = Split (objInputFileFromKardy.ReadAll, vbNewLine)
    'Résultats Null listes
    UserDisables = ""
    UserUpdated = ""
    UserNoFound = ""
    UserDuplicated = ""
    ii = 0


    Pour chaque strFULL En inputDataFromFiried
    si Len (strFULL)> 5 puis
    'Zero sur le comptoir des correspondances trouvées
    e = 0
    '1er champ: sélectionner les lignes du nom d'utilisateur
    strFIO = Gauche (strFULL, InStr (strFULL, ";") - 1)
    «Diviser en parties Nom
    Familia = Gauche (strFIO, (Instr (strFIO "," -1)))
    N = trim (mid (strFIO, Instr (strFIO, "")))
    Imya = Gauche (N, (Instr (N ",") -1))
    Otchestvo = trim (mi (N, Instr (N, "")))
    "Mettre en pièces Nom
    strFIO = Familia & "" & Imya & "" & Otchestvo

    index = maxindex
    Alors que l'indice> 1

    «Diviser par les parties en nommer AD

    AdFamilia = ""
    AdImya = ""
    AdOtchestvo = ""
    AdFamilia = Gauche (MFullName (index), (Instr (MFullName (index) "," -1)))
    si Len (Trim (mid (MFullName (index), Instr (MFullName (index), ""))))> 1 alors
    AdN = trim (mid (MFullName (index), Instr (MFullName (index), "")))
    si Len (Gauche (AdN, (Instr (AdN, ""))))> 1 alors
    AdImya = Gauche (AdN, (Instr (AdN, "") -1))
    si Len (Trim (mid (AdN, Instr (AdN, ""))))> 1 alors
    AdOtchestvo = trim (mid (AdN, Instr (AdN, "")))
    fin si
    fin si

    fin si


    "Mettre en pièces Nom
    AdstrFIO = AdFamilia & "" & AdImya & "" & AdOtchestvo
    AdstrFIO1 = AdImya & "" & AdOtchestvo & "" & AdFamilia
    AdstrFIO2 = AdImya & "" & AdFamilia & "" & AdOtchestvo
    'Wscript.Echo AdstrFIO

    if (StrFIO = AdstrFIO) ou (StrFIO = AdstrFIO1) ou (StrFIO = AdstrFIO2) puis
    e = e + 1
    Mindex = index
    fin si
    index = index-1
    Wend


    si e = 1 alors
    «Suspendre connexion à AD
    LockUser (Mlogins (Mindex))
    UserDisables = UserDisables & "Utilisateur:" & strFIO & "est désactivée" & vbCrLf
    fin si
    'Ne pas bloquer l'ouverture / depuis nous avons plus de la même nom trouvé
    si e> 1, alors
    UserNoFound = UserNoFound & "Utilisateur:" & strFIO et "se trouve plus de 1 fois" & vbCrLf
    fin si
    'Ne pas bloquer l'ouverture / depuis utilisateur introuvable
    si e = 0 alors
    UserDuplicated = UserDuplicated & "Utilisateur:" & strFIO & "n'a pas été trouvé" & vbCrLf
    fin si

    fin si


    suivant






    «S'il n'y a aucun résultat, alors
    if (len (UserDisables) + len (UserNoFound) + len (UserDuplicated)> 10), puis
    «Commencer à envoyer du courrier

    Set objNetwork = CreateObject ( "Wscript.Network")
    objComputerName = objNetwork.ComputerName
    objUserName = objNetwork.UserName
    Set objMessage = CreateObject ( "CDO.Message")
    objMessage.From = "<e-mail de quelqu'un courrier envoyé>"
    objMessage.To = "<e-mail quelqu'un courrier envoyé>"
    objMessage.Subject = "Sujet"

    'Kodirovochku Mettre
    objMessage.bodypart.charset = "koi8-r"
    objMessage.TextBody = UserDisables & vbCrLf & UserNoFound & vbCrLf & UserDuplicated
    objMessage.Configuration.Fields.Item _
    ( "Http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    'Nom ou IP du serveur distant SMTP
    objMessage.Configuration.Fields.Item _
    ( "Http://schemas.microsoft.com/cdo/configuration/smtpserver") = "<adresse du serveur smtp>"
    'Port du serveur (en général 25)
    objMessage.Configuration.Fields.Item _
    ( "Http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    objMessage.Configuration.Fields.Update
    '== Fin section de configuration du serveur SMTP distant ==

    objMessage.Send


    fin si



    objInputFileFromKardy.Close
    Réglez objFileSystem = Nothing
    Sous LockUser (strText)
    'Dans cette valeur de ligne TRUE - diseyblit utilisateur, FALSE - ouvre l'utilisateur
    strDisableAccount = TRUE

    strUserLogin = strText
    définir objUser = GetObject ( "WinNT: // <domain> /" & strUserLogin & ", l'utilisateur")


    si strDisableAccount = TRUE
    objUser.AccountDisabled = strDisableAccount
    objUser.Description = "Le compte est désactivé en raison de tir" et "à" & "" & Date ()
    objUser.SetInfo
    fin si

    si strDisableAccount = FALSE
    objUser.AccountDisabled = strDisableAccount
    objUser.Description = "compte est ouvert par le script" et "à" & "" & Date ()
    objUser.SetInfo
    fin si


    End Sub





    Ce script est utilisé pour copier le fichier sur les profils utilisateur d'itinérance:

    // ************************************************ *****************************
    // JScript 2004 Shs
    // Ce script est utilisé pour copier le fichier sur les profils utilisateur d'itinérance
    // (Ajouter un tag dans le menu utilisateur)
    // ************************************************ ******************************
    //
    //
    // ************************************************ *****************************
    // Fonction récursive déplacer tous les sous-répertoires commençant par le travail (PolFldr)
    // Et copier le fichier spécifié (ScriptName) sur le dossier Tâches (FldrName)
    // ************************************************ ******************************
    LoopSubFolders de fonction (PolFldr, DeepCount)
    {
    SubFolders var, // Stratégies système Collection podkatologov
    fsoPolFldr, // l'objet pour accéder au dossier
    CurFldr; // Dossier actuel

    DeepCount ++;
    //WScript.Echo(DeepCount);
    if (DeepCount <DeepLimit)
    {
    fsoPolFldr = FSO.GetFolder (PolFldr);
    // Obtenir une collection de politiques sous-répertoires système
    SubFolders = new recenseur (fsoPolFldr.SubFolders);
    //
    pour (;! SubFolders.atEnd (); SubFolders.moveNext ())
    {
    SubFolders.item CurFldr = ();
    if (CurFldr.Name == FldrName)
    {
    try {
    WScript.Echo (CurFldr.Path + "\\" + ScriptName);
    //WScript.Echo(Path2Scripts + "\\" + ScriptName);
    FSO.CopyFile (Path2Scripts + "\\" + ScriptName, CurFldr.Path + "\\" + ScriptName, true)
    }
    catch (e)
    {// erreurs Handle
    var Msg;
    if (! e = 0) Msg = "Erreur -" + e.description
    autre Msg = "Ok";
    WScript.Echo (Msg);
    }
    }
    // Appel récursif
    (LoopSubFolders CurFldr, DeepCount);
    } // Fin de boucle
    } // Fin de si
    }
    // ************************************************ ********************************

    //
    //


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

    // Cap
    // ************************************************ ********************************

    // Le code va ici, obtenir à partir des options de ligne de commande
    // 1) le nom du fichier lorsque les pairs
    // 2) le nom du répertoire dans chaque profil, qui sera copié fichier distribué
    // ************************************************ ********************************

    var ScriptName = "Mettre à jour le menyu.lnk travail"
    FldrName = "Menu principal"; // Le nom des sous-dossiers dans le profil (il copie le raccourci-file)
    // ************************************************ ********************************
    **




    // ************************************************ ********************************
    *
    // Déclaration des variables globales
    // ************************************************ ********************************
    *
    var FSO, // object FileSystemObject
    Path2Scripts, // rasprostronyaetsya le chemin du fichier (en supposant que les fichiers sont dans le même dossier que le fichier)
    DeepCount, // profondeur compteur de récursivité
    DeepLimit, // Limiter la profondeur de récursivité
    POLF; // Racine à partir duquel débuter la recherche et la diffusion sur les dossiers de fichiers sous-jacents
    // ************************************************ ********************************
    *
    POLF = "OZI \\ \\\\ DC \\ UserFolders"; ////
    // Création d'un objet FileSystemObject;
    FSO = WScript.CreateObject ( "Scripting.FileSystemObject");
    DeepCount = 0;
    Path2Scripts = FSO.GetParentFolderName (FSO.GetFile (WScript.ScriptFullName));
    // Limite la profondeur des appels récursifs
    DeepLimit = 4;
    LoopSubFolders (POLF, DeepCount);





    Iventarizatsiya toutes les machines dans le domaine:

    strclass dim, objAD, obj
    invdate dim
    constmb dim, constgb, sizegb
    COMPNAME dim, 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")

    définir objAD = GetObject ( "LDAP: // CN = Computers, DC = aaa, DC = bbb, DC = ccc")
    objAD.filter = array ( "computer")
    On Error Resume Next
    pour chaque obj dans objAD
    Compad = droite (obj.name, len (obj.name) -3)
    invdate = date
    temp = "<html>" + chr (10) + "Date de collection:" & invdate & "<table>" + chr (10)
    COMPNAME = ""
    'On Error Resume suivant
    définir objWMIService = GetObject ( "winmgmts: //" & Compad & "/ root \ cimv2")
    i = 0
    s = 0
    d = 0
    q = 0
    'Sizegb = ""
    a = 0-8
    Set colItems = objwmiservice.instancesof (strclass (a))
    pour chaque objItem dans colItems
    sélectionnez un cas
    cas 0
    temp = température + "<tr> <td>"
    temp = température + "Nom de l'ordinateur" + "</ td> <td>" objitem.name + "</ td>" + chr + (10)
    temp = température + "</ tr>" + chr (10)
    temp = température + "<tr> <td>"
    temp = température + "RAM" + "</ td> <td>" + cstr (round (objitem.totalphysicalmemory / constmb)) + "MB </ td>" + chr (10)
    temp = température + "</ tr>" + chr (10)
    temp = température + "<tr> <td>"
    temp = température + "modèle informatique" "</ td> <td>" objitem.model + "</ td>" + chr + + (10)
    temp = température + "</ tr>" + chr (10)
    COMPNAME = objitem.name
    cas 1
    temp = température + "<tr> <td>"
    temp = température + "carte mère" "</ td> <td>" objitem.SMBIOSBIOSVersion + "</ td>" + chr + + (10)
    temp = température + "</ tr>" + chr (10)
    temp = température + "<tr> <td>"
    temp = température + "BIOS" + "</ td> <td>" + objitem.caption + "</ td>" + chr (10) + "<td>" + chr (10) + "</ td>"
    temp = température + "</ tr>" + chr (10)
    cas 2
    s = s + 1
    temp = température + "<tr>" + chr (10) + "<td>"
    temp = température + "processeur" + cstr (s) + "</ td>" + chr (10) + "<td>" + objitem.name + "fréquence" + cstr (objitem.CurrentClockSpeed) + chr (10) + " </ td> "
    temp = température + "</ tr>" + chr (10)
    cas 3
    i = i + 1
    temp = température + "<tr>" + chr (10) + "<td>"
    si objitem.size> 0 puis '= nill puis
    sizegb = cstr (round (objitem.size / constgb, 2))
    autre
    sizegb = cstr (0)
    fin si
    temp = température + "Disque dur" + cstr (i) + "</ td>" + chr (10) + "<td>" + objitem.model + "" + sizegb + "GB </ td>" + chr ( 10)
    temp = température + "</ tr>" + chr (10)
    4 cas
    temp = température + "<tr>" + chr (10) + "<td>"
    temp = température + + "</ td>" + chr "Videokontroler" (10) + "<td>" + objitem.caption + chr (10) + "</ td>"
    temp = température + "</ tr>" + chr (10)
    cas 5
    si objitem.adaptertypeid = 0 et objitem.netconnectionstatus = 2 alors
    temp = température + "<tr>" + chr (10) + "<td>"
    temp = température + "carte réseau" + "</ td>" + chr (10)
    temp = température + "<td>" + objitem.name + chr (10) + "</ td>"
    temp = température + "</ tr>" + chr (10)
    fin si
    6 cas
    temp = température + "<tr>" + chr (10) + "<td>"
    temp = température + "carte son" + "</ td>" + chr (10)
    temp = température + "<td>" + objitem.caption + chr (10) + "</ td> </ tr>" + chr (10)
    7 cas
    temp = température + "<tr>" + chr (10) + "<td>"
    temp = température + "adaptateur SCSI" + "</ td>" + chr (10)
    temp = température + "<td>" + objitem.manufacturer + "" + objitem.caption + chr (10) + "</ td> </ tr>" + chr (10)
    8 cas
    d = d + 1
    temp = température + "<tr>" + chr (10) + "<td>"
    temp = température + "imprimante" + cstr (d) + "</ td>" + chr (10) + "<td>" + objitem.name + chr (10) + "</ td>"
    temp = température + "</ tr>" + chr (10)
    End Select
    suivant
    suivant
    «La dernière partie
    temp = température + "</ table> </ html>"
    'Record File
    Dim fso, tf
    Set fso = CreateObject ( "Scripting.FileSystemObject")
    Set tf = fso.CreateTextFile ( "\\ servak ​​\ comp \" & COMPNAME & ". Htm", True)
    tf.Write (temp)
    tf.Close
    suivant





    Déterminer quand un compte Expire (Retourne la date d'expiration pour un compte d'utilisateur):

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

    dtmAccountExpiration = objUser.AccountExpirationDate

    Si Err.Number = -2147467259 Ou _
    dtmAccountExpiration = "1/1/1970" Ensuite,
    WScript.Echo "Pas de compte expiration spécifié"
    autre
    WScript.Echo "Compte expiration:" & _
    objUser.AccountExpirationDate
    End If





    Déterminer quand un compte d'utilisateur Expire (Rapports de la date à laquelle le compte d'utilisateur Active Directory MyerKen expire.):
      On Error Resume Next 
    Set objUser = GetObject _
    ( "LDAP: // cn = MyerKen, ou = Gestion, dc = NA, dc = fabrikam, dc = com")
    dtmAccountExpiration = objUser.AccountExpirationDate

    Si Err.Number = -2147467259 Ou dtmAccountExpiration = "1/1/1970" Ensuite,
    WScript.Echo "Pas de compte expiration spécifié"
    autre
    WScript.Echo "Compte expiration:" & objUser.AccountExpirationDate
    End If





    Le script définit récursivement tous les attributs des utilisateurs du domaine " L' utilisateur doit changer le mot de passe sur la prochaine ouverture de session ": PS Ddlya fonctionne correctement, vous devez définir un nom de domaine strMyDomain variable à partir du point de vue de l'annuaire LDAP - qui est, tous les points remplacés par "DC =". Ainsi, le domaine argo.com converti en DC = argo, DC = com dans la variable strMyOU doit placer le nom et l'Unité d'organisation, les utilisateurs qui ont besoin d'exposer la procédure de changement de mot de passe.

    Dim strMyOU
    Dim strMyDomain

    Dim objOU, objUser
    Dim strContainer, strLastUser

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

    sous se reproduit (ou)
    strContainer = "OU =" + ou + "," + strMyDomain
    définir objOU = GetObject ( "LDAP: //" & strContainer)
    Pour chaque objUser dans objOU
    strLastUser = objUser.Get ( "name")
    Si objUser.Class = "organizationalUnit" Ensuite,
    se reproduit (strLastUser + ", OU =" + ou)
    Elseif objUser.Class = "user" Ensuite,
    objUser.Put "pwdLastSet", 0
    objUser.SetInfo
    fin si
    suivant
    End Sub

    strMyOU se reproduit

    WScript.Quit





    Préparation SID (a) un ordinateur de 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) et "-" & Convert (12,15) et "-" & Convert (8,11) et "-" & Convert (4,7) et "-" & Convert (0,3)
    Réglez objGroup = Nothing

    fonction Convert (u, l)
    Tmp = ""
    Pour x = UBound (Sid) -u à ​​UBound (Sid) Étape -l -1
    b = AscB (MIDB (SID, x + 1))
    Tmp = Tmp & Hex (b \ 16) & Hex (b et 15)
    suivant
    Convertir = Clng ( "& H" & Tmp)
    end function
    wscript.echo (GSID)





    Поиск аккаунтов в ActiveDirectory с просроченными паролями : Если NetBIOS имя домена отличается от DNS до первой точки, то руками вместо строки dom=getObject("LDAP://" & DC).get("Name") присвоить нужное значение

    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)
    suivant
    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)
    suivant
    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
    suivant

    ' Создание логов
    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


    suivant

    'Закрытие логов
    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 = "[email protected]"
    objEmail.To = rs.Fields("mail")
    'Optional BCC field
    'objEmail.BCC = "[email protected]"
    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
    suivant

    Set Conn = Nothing
    For Each clsConn in colNetwork.Items
    If Instr(LCase(clsConn.name), LCase(strConn)) Then
    ' получение указанного подключения
    Set Conn = clsConn
    Exit For
    End If
    suivant
    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
    suivant

    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