//*****************************************************
//JScript 2005 ShS addPrn.js
//Подключение сетевого принтера и установка его принтером по умолчанию
//Пример запуска: %LOGONSERVER%\NETLOGON\addPrn.js \\PrintServer\HPLJ2200DN(23)
//*****************************************************
var WshNetwork,
objArgs,
strErrMsg,
strPrinterPath;
//Путь к подключаемому принтеру берем из параметров запуска
objArgs=WScript.Arguments.Unnamed;
strPrinterPath=objArgs.Item(0);
//
WshNetwork=WScript.CreateObject("Wscript.Network");
try
{
WshNetwork.AddWindowsPrinterConnection(strPrinterPath);
WshNetwork.SetDefaultPrinter(strPrinterPath);
}
catch (objError)
{
if (objError !=0)
{
strErrMsg = "Произошла ошибка при пордключении сетевого принтера - "+strPrinterPath+"\n"+
"Скорее всего узанный сетевой путь не существует"+"\n\n"+
"Обратитесь к системному администратору по тел. 1333"
//"Код ошибки: "+ objError.number;
WScript.Echo(strErrMsg);
}
}
Const APPLICATION_DATA = &H1a&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(APPLICATION_DATA)
Set objFolderItem = objFolder.Self
'On Error Resume Next
ParentFolder = objFolderItem.Path &"\Microsoft"
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(ParentFolder)
objFolder.NewFolder "Signatures"
'On Error Resume Next
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(APPLICATION_DATA)
Set objFolderItem = objFolder.Self
'Копирование графики в папку пользователя
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.Shell")
strCopyFrom = "\\adm\Софт\Шаблон подписи Microsoft Office Outlook\VSV\"
objFSO.CopyFile strCopyFrom & "new-logo_go.gif", WshShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Application Data\Microsoft\Signatures\"
objFSO.CopyFile strCopyFrom & "new-ugolok.gif", WshShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Application Data\Microsoft\Signatures\"
objFSO.CopyFile strCopyFrom & "re-ugolok.gif", WshShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Application Data\Microsoft\Signatures\"
objFSO.CopyFile strCopyFrom & "newcompany.htm", WshShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Application Data\Microsoft\Signatures\"
objFSO.CopyFile strCopyFrom & "recompany.htm", WshShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Application Data\Microsoft\Signatures\"
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objRegExp = CreateObject("VBScript.RegExp")
objRegExp.IgnoreCase = False ' учитывать регистр символов
objRegExp.Multiline = True ' многострочный объект
objRegExp.Global = True ' Ищем по всему тексту
'Подключаем ADSystemInfo'
Set objSysInfo = CreateObject("ADSystemInfo")
strUser = objSysInfo.UserName
Set objUser = GetObject("LDAP://" & strUser)
'New Фамилия Имя'
Set objTextFile = objFSO.OpenTextFile (objFolderItem.Path &"\Microsoft\Signatures\newcompany.htm", ForReading, False)
strTextFile = objTextFile.ReadAll
objTextFile.Close
objRegExp.Pattern = "Фамилия Имя"
strName = objUser.FullName
strName = InputBox ("Добро пожаловать в программу настройки подписи Outlook. Измените ФИО так как они должны выглядеть в подписи", "ФИО", strName)
strTextFile = objRegExp.Replace(strTextFile,strName)
Set objTextFile = objFso.OpenTextFile(objFolderItem.Path &"\Microsoft\Signatures\newcompany.htm", ForWriting, False)
objTextFile.Write strTextFile
objTextFile.Close
'RE Фамилия Имя'
Set objTextFile = objFSO.OpenTextFile (objFolderItem.Path &"\Microsoft\Signatures\recompany.htm", ForReading, False)
strTextFile = objTextFile.ReadAll
objTextFile.Close
objRegExp.Pattern = "Фамилия Имя"
strTextFile = objRegExp.Replace(strTextFile,strName)
Set objTextFile = objFso.OpenTextFile(objFolderItem.Path &"\Microsoft\Signatures\recompany.htm", ForWriting, False)
objTextFile.Write strTextFile
objTextFile.Close
'New Email'
Set objTextFile = objFSO.OpenTextFile (objFolderItem.Path &"\Microsoft\Signatures\newcompany.htm", ForReading, False)
strTextFile = objTextFile.ReadAll
objTextFile.Close
objRegExp.Pattern = "href='mailto:mymail@company.ru'>mymail@company.ru"
strEmail = objUser.mail
strEmail = "href='mailto:" & strEmail & "'>" & strEmail
strTextFile = objRegExp.Replace(strTextFile,strEmail)
Set objTextFile = objFso.OpenTextFile(objFolderItem.Path &"\Microsoft\Signatures\newcompany.htm", ForWriting, False)
objTextFile.Write strTextFile
objTextFile.Close
'Re Email'
Set objTextFile = objFSO.OpenTextFile (objFolderItem.Path &"\Microsoft\Signatures\recompany.htm", ForReading, False)
strTextFile = objTextFile.ReadAll
objTextFile.Close
objRegExp.Pattern = "href='mailto:mymail@company.ru'>mymail@company.ru"
strTextFile = objRegExp.Replace(strTextFile,strEmail)
Set objTextFile = objFso.OpenTextFile(objFolderItem.Path &"\Microsoft\Signatures\recompany.htm", ForWriting, False)
objTextFile.Write strTextFile
objTextFile.Close
'New Должность'
Set objTextFile = objFSO.OpenTextFile (objFolderItem.Path &"\Microsoft\Signatures\newcompany.htm", ForReading, False)
strTextFile = objTextFile.ReadAll
objTextFile.Close
objRegExp.Pattern = "Должность"
strTitle = InputBox ("Введите Вашу должность, например: Системный администратор", "Должность")
strTextFile = objRegExp.Replace(strTextFile,strTitle)
Set objTextFile = objFso.OpenTextFile(objFolderItem.Path &"\Microsoft\Signatures\newcompany.htm", ForWriting, False)
objTextFile.Write strTextFile
objTextFile.Close
'Re Должность'
Set objTextFile = objFSO.OpenTextFile (objFolderItem.Path &"\Microsoft\Signatures\recompany.htm", ForReading, False)
strTextFile = objTextFile.ReadAll
objTextFile.Close
objRegExp.Pattern = "Должность"
strTextFile = objRegExp.Replace(strTextFile,strTitle)
Set objTextFile = objFso.OpenTextFile(objFolderItem.Path &"\Microsoft\Signatures\recompany.htm", ForWriting, False)
objTextFile.Write strTextFile
objTextFile.Close
'New Телефон'
Set objTextFile = objFSO.OpenTextFile (objFolderItem.Path &"\Microsoft\Signatures\newcompany.htm", ForReading, False)
strTextFile = objTextFile.ReadAll
objTextFile.Close
objRegExp.Pattern = "Тел.:"
strPhone = InputBox ("Введите номер внутреннего телефона (четыре цифры, например, 7550)", "Телефон")
If strPhone <> "" then
strPhone = "Тел.: +7 (812) 111-11-11 (доб. " & strPhone & ")"
else
strPhone = "Тел.: +7 (812) 111-11-11"
end if
strTextFile = objRegExp.Replace(strTextFile,strPhone)
Set objTextFile = objFso.OpenTextFile(objFolderItem.Path &"\Microsoft\Signatures\newcompany.htm", ForWriting, False)
objTextFile.Write strTextFile
objTextFile.Close
'Re Телефон'
Set objTextFile = objFSO.OpenTextFile (objFolderItem.Path &"\Microsoft\Signatures\recompany.htm", ForReading, False)
strTextFile = objTextFile.ReadAll
objTextFile.Close
objRegExp.Pattern = "Тел.:"
strTextFile = objRegExp.Replace(strTextFile,strPhone)
Set objTextFile = objFso.OpenTextFile(objFolderItem.Path &"\Microsoft\Signatures\recompany.htm", ForWriting, False)
objTextFile.Write strTextFile
objTextFile.Close
'New Мобильный Телефон'
Set objTextFile = objFSO.OpenTextFile (objFolderItem.Path &"\Microsoft\Signatures\newcompany.htm", ForReading, False)
strTextFile = objTextFile.ReadAll
objTextFile.Close
objRegExp.Pattern = "<!--Mobile-->"
strMobile = InputBox ("Введите номер мобильного телефона или оставьте поле пустым, если он не нужен", "Мобильный телефон")
If strMobile <> "" then
strMobile = "<span style=""font-size:8.5pt;font-family:'Arial Narrow','sans-serif'; color:#C80000"">Моб.: " & strMobile & "</span><br>"
end if
strTextFile = objRegExp.Replace(strTextFile,strMobile)
Set objTextFile = objFso.OpenTextFile(objFolderItem.Path &"\Microsoft\Signatures\newcompany.htm", ForWriting, False)
objTextFile.Write strTextFile
objTextFile.Close
'Re Мобильный Телефон'
Set objTextFile = objFSO.OpenTextFile (objFolderItem.Path &"\Microsoft\Signatures\recompany.htm", ForReading, False)
strTextFile = objTextFile.ReadAll
objTextFile.Close
objRegExp.Pattern = "<!--Mobile-->"
strTextFile = objRegExp.Replace(strTextFile,strMobile)
Set objTextFile = objFso.OpenTextFile(objFolderItem.Path &"\Microsoft\Signatures\recompany.htm", ForWriting, False)
objTextFile.Write strTextFile
objTextFile.Close
'Прописываем подпись в реестре
Const HKEY_CURRENT_USER = &H80000001
strComputer = "."
Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
'Получаем профиль по умолчанию'
strProfilesPath = "Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles"
intRes = objReg.GetStringValue(HKEY_CURRENT_USER,strProfilesPath,"DefaultProfile",strValue)
'Заносим в реестр подписи'
strKeyPath = "Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\" & strValue & "\9375CFF0413111d3B88A00104B2A6676\00000002"
strValueName = "New Signature"
strValueName2 = "Reply-Forward Signature"
aValueData = Array(&H6e,&H00,&H65,&H00,&H77,&H00,&H6e,&H00,&H65,&H00,&H6f,&H00,&H70,&H00,&H72,&H00,&H69,&H00,&H6e,&H00,&H74,&H00)
aValueData2 = Array(&H72,&H00,&H65,&H00,&H6e,&H00,&H65,&H00,&H6f,&H00,&H70,&H00,&H72,&H00,&H69,&H00,&H6e,&H00,&H74,&H00,&H00,&H00)
objReg.SetBinaryValue HKEY_CURRENT_USER,strKeyPath,strValueName,aValueData
objReg.SetBinaryValue HKEY_CURRENT_USER,strKeyPath,strValueName2,aValueData2
MsgBox ("Подпись настроена. Перезапустите Outlook чтобы применились настройки")
$InactiveDays = New-TimeSpan -days 56
$LastLogonTimeMark= (get-date) - $InactiveDays
#
Get-QADComputer -IncludedProperties lastLogontimeStamp, useraccountcontrol|
?{$_.lastLogontimeStamp -lt $LastLogonTimeMark}|
select name, lastLogontimeStamp, whenCreated, @{Name="Disabled"; Exp={$_.useraccountcontrol -band 2}}|
?{$_.Disabled -eq 0}|
sort lastLogontimeStamp| ft Name,lastLogonTimeStamp, whenCreated, Disabled -AutoSize
<# Скрипт Get-LogOnOffEvts.ps1 shs 20101112
.Synopsis
Скрипт проводит опрос компьютеров, чьи учетные записи находятся в заданном параметрами запуска OU,
собирая информацию о событиях входа/выхода и сохраняя их в файл отчета
Get-LogOnOffEvts.ps1 [SearchRoot] [SearchScope] [DateBefore] [DateAfter] <ReportFileName>
.Parameters
SearchRoot - задает корневой контейнер, с которого будет начат поик учетных записей компьютеров,
подлежащих опросу
Если не задано иное, то по умолчанию принимает значение "$(([ADSI]"LDAP://rootDSE").rootDomainNamingContext)",
которое равно DN корневого домена леса.
SearchScope - область поиска, может принимать одно из 3х возможных значений:
'Base' - ограничивает область поиска базовым объектом (SearchRoot)
'OneLevel' - поиск только прямых потомков базового объекта (SearchRoot),
за исключением самого базового объекта
'Subtree' - поиск по всему поддереву, начиная с базового объекта (SearchRoot),
включая сам базовый объект
Если не задано иное, то по умолчанию принимает значение 'Subtree'
DateBefore - верхня граница даты искомых событий (по умолчанию - начало следующих суток)
DateAfter - нижняя граница даты искомых событий (по умолчанию - начало текущих суток)
ReportFileName -полное имя файла отчета
.Examples
Get-LogOnOffEvts.ps1 -ReReportFileName c:\temp\report.csv
Get-LogOnOffEvts.ps1 -SearchBase "domain.local/MyOU/Workstations" -ReReportFileName c:\temp\report.csv
Get-LogOnOffEvts.ps1 -SearchBase "domain.local/MyOU/Workstations" -SearchScope 'OneLevel' -ReReportFileName c:\temp\report.csv
Get-LogOnOffEvts.ps1 -SearchBase "CN=MyComp,OU=Workstations,OU=MyOU,DC=domain,DC=local" -DateAfter "30/04/2010" -ReReportFileName c:\temp\report.csv
#>
#================================================================================================================
param($SearchRoot="dom.local/RTA/Workstations", [DirectoryServices.SearchScope]$SearchScope="Subtree",`
[DateTime]$DateBefore=(Get-Date).AddDays(1).Date, [DateTime]$DateAfter=(Get-Date).Date, $ReportFileName)
#================================================================================================================
<###############################################################################
Function Show-Help. Выыодит на экран первый блочный коментарий скрипта,
заданного в качестве параметра вызова.
.Parameter <ScriptFullName>
Полное имя скрипта, чей первый блочный коментарий будет выведен на экран.
#################################################################################>
Function Show-Help ($ScriptFullName){
if ($ScriptFullName) {
$IsHelpLine=$false
switch -file $ScriptFullName {
{$_ -match "<#"} {Write-Host $_;$IsHelpLine=$true;continue}
{$_ -match "#>"} {Write-Host $_;$IsHelpLine=$false;break}
{$IsHelpLine} {Write-Host $_;}
}
}
}
<###############################################################################
Функция Get-LogonLogoffEvts предназначена для получения массива объектов,
содержащих информацию о событиях входа/ выхода на заданном компьютере
(Будет собрана информация о событиях с event id равными 528,528,540)
.Parameters
CompName - Имя опрашиваемого компьютера
Before - Верхняя граница даты искомых событий
After - Нижняя граница даты искомых событий
###############################################################################>
Function Get-LogonLogoffEvts ($CompName, $Before=$DateBefore, $After=$DateAfter) {
#массив, в который будем собирать информацию входа/выхода для заданного компьютера
$arrLogOnOffEvts=@()
#Перебираем все события с EventID равными 528|538 в заданном диапазоне даты/времени
#Get-EventLog -ComputerName $CompName -InstanceId 528,538 -LogName Security -After $After -Before $Before|%{
$filter="logfile='Security' and (eventcode='528' or eventcode='540' or eventcode='538') and TimeGenerated >= '$([System.Management.ManagementDateTimeConverter]::ToDMTFDateTime($After))'"
$filter+= " and TimeGenerated <= '$([System.Management.ManagementDateTimeConverter]::ToDMTFDateTime($Before))'"
gwmi -ComputerName $CompName -Class Win32_NTlogEvent -Filter $filter -ErrorAction Stop|%{
#создадим новый объект, в который будем записывать информацию об очередном событии входа/выхода
$objLogOnOffEvt=New-Object PSObject -Property @{
CompName=$CompName;
TimeGenerated=$null;
User=$null;
Domain=$null;
EventIdentifier=$null;
LogonType=$null;
}
#и сохраняем всю полезную информацию о событии в объете $objLogOnOffEvt
$objLogOnOffEvt.TimeGenerated=[datetime]$_.TimeGenerated
$objLogOnOffEvt.EventIdentifier=$_.EventIdentifier
switch -regex ($_.Message) {
"Пользователь:\t+(\w+(?:\s?[\w-]+)*)" {$objLogOnOffEvt.User=$Matches[1]}
"Домен:\t+(\w+(?:\s?[\w-]+)*)" {$objLogOnOffEvt.Domain=$Matches[1]}
"Тип входа:\t+(\d+)" {$objLogOnOffEvt.LogonType=$Matches[1]}
}
#добавляем информацию об очередном событии в массив
#$objLogOnOffEvt
$arrLogOnOffEvts+=$objLogOnOffEvt
}
#возвращаем, как результат работы функции, информацию о всех собранных событиях
$arrLogOnOffEvts
}
#
#====================================== Точка входа скрипта ==================================
#если полное имя файла отчета задано и задано правильно (путь в полном имени файла указывает на папку,
#которая реально существует), то начинаем работу
if (($ReportFileName) -and (Test-Path ($ReportFileName|Split-Path))) {
#Массив, в который будем собирать информацию о событиях входа/выхода, собранную со всех опрашиваемых компьютеров
$arrReport=@()
#Выбираем из заданной ветки все неотключенные учетные записи компьютеров
$arrComps = Get-QADComputer -ErrorAction SilentlyContinue -SearchRoot $SearchRoot -SearchScope $SearchScope -SizeLimit 0 |
select name, @{Name="Disabled"; Exp={$_.useraccountcontrol -band 2}}|
?{$_.Disabled -eq 0}| select -ExpandProperty name
#можно было бы и далше продолжать передавать данные по конвейеру, но мы не будем этого делать
#(чтобы упростить отладку и облегчить восприятие)
#для каждого компьютера из списка...
$arrComps|foreach {
##...если компьютер доступен (пингуется)...
if (Test-Connection $_ -Count 1 -Quiet) {
Write-Host "`n$_" -NoNewline
try {
###...добавляем информацию о событиях входа/выхода опрашиваемого компьютера к общему отчету
$arrReport+=Get-LogonLogoffEvts $_
}
catch {
Write-Host "`t-->`t Ошибка доступа!" -ForegroundColor Red -NoNewline
}
}
}
#Выгружаем сформированный отчет в файл-csv, который удобно обрабатывать в excel
$arrReport|Export-Csv -Path $ReportFileName -UseCulture -Encoding Default
}
else {
#Выводим на экран первый блочный комментарий этого скрипта в качестве справки
Show-Help $MyInvocation.MyCommand.Path
}
strComputer = InputBox("Имя компа?")
strProctarget = InputBox("имя_процесса")
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objWMIService = objSWbemLocator.ConnectServer(strComputer, _
"root\CIMV2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = '" _
& strProctarget & "'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next
Set fso = CreateObject("Scripting.FileSystemObject")
Set Text = fso.CreateTextFile("passwords.txt")
dim a, DesiredLength, DesiredCount
DesiredLength = inputbox ("Введите длину пароля")
DesiredCount = inputbox ("Введите количество паролей")
FOR a=1 to DesiredCount
Randomize( )
dim CharacterSetArray
CharacterSetArray = Array( _
Array( DesiredLength, "~!@#$%^&*()_+-=[]{};':,./<>?0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" ) _
)
dim i
dim j
dim Count
dim Chars
dim Index
dim Temp
Count = CharacterSetArray( 0 )( 0 )
Chars = CharacterSetArray( 0 )( 1 )
for j = 1 to Count
Index = Int( Rnd( ) * Len( Chars ) ) + 1
Temp = Temp & Mid( Chars, Index, 1 )
next
dim TempCopy
do until Len( Temp ) = 0
Index = Int( Rnd( ) * Len( Temp ) ) + 1
TempCopy = TempCopy & Mid( Temp, Index, 1 )
Temp = Mid( Temp, 1, Index - 1 ) & Mid( Temp, Index + 1 )
loop
RandomString = TempCopy
Text.WriteLine(RandomString)
TempCopy=""
Rnd( )
next
Text.Close
Dim WSHShell
Set WSHShell = WScript.CreateObject("WScript.Shell")
WSHShell.Run "notepad.exe passwords.txt"
Set WSHShell = Nothing
'Wscript.Sleep 1000
'FSO.DeleteFile("passwords.txt")
l>Xm}~phBqBO+.ar^*W.97u5N;%cADK^
T#*[o1pDO?yq5~s:@CV*BUB/1bU9BOA!
r@WKgV;b_nNA$:ll0*$}Rcc-rJ5rRZoT
N2('q1@<31N9+ul!RFMXSwl;@XB>Vtc%
I]u='FW^Vx;z{,v4{Gkh+A]T{{+(dD!;
09H%#[U1=m3^au{C,.4bAG3@da}_1x3H
ID/w}fN&xt:OJI/Vt='KZp4}}23d;NW&
+mB*<5iezdoeOK@<yu)%r&M{2Tdq<j_J
O*g>%-YkZ<19c/#?0as4W2+V9l>K%.gt
J/d'grTx4Sw')t8l@(d_E5NG=rqx;kSF
Option Explicit
Dim oFSO, oFso1, objFile, objFile1, objRegExp
dim strFileName, strOutputFilename, strLine
dim objMatches, objSubmatches
strFilename="input.txt" 'Исходный файл
strOutputFilename="out.txt" 'Файл для вывода
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFSO1 = CreateObject("Scripting.FileSystemObject")
Set objRegExp = CreateObject("VBScript.RegExp") 'Создается объект регулярных выражений
objRegExp.Pattern = "test" 'Указывается ключевые слова поиска
objRegExp.IgnoreCase = True 'Указывается независимость от регистра символов
Set objFile = oFSO.OpenTextFile(strFileName, 1) ' Открываем файл на чтение
Set objFile1 = oFSO1.OpenTextFile(strOutputFileName, 2, True) ' Открываем файл на перезапись
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine 'Читаем 1 строку файла
objRegExp.Pattern = "([\d]+\.[\d]+\.[\d]+)[\s]+([\w]+)[\s]+([\d]+)[\s]+([\d]+)[\s]+(.+)$"
Set objMatches = objRegExp.Execute(StrLine)
if objMatches.count=1 then
objFile1.Writeline ( _
objMatches.item(0).Submatches(0) & " " & _
objMatches.item(0).Submatches(1) & " " & _
objMatches.item(0).Submatches(2) & " " & _
objMatches.item(0).Submatches(4) _
)
end if
Loop
objFile.Close ' Закрываем файл
objFile1.Close ' Закрываем файл
<#***************************************************
PowerShell 2012 iura
Создание папок для хранения перемещаемых профилей пользователей Active Directory.
Актуально для сетевых хранилищ под управлением *nix-систем
Logon Name пользователя берётся из файла,
где каждая учётная запись начинается с новой строки
Пример содержания файла users.txt:
user1
user2
...
userN
При использовании другого форматирования или форматов данных,
пожалуйста, используйте параметры команды Get-Content и опцию -Delimeter
***************************************************** #>
#Открываем нужный нам файл
$users = Get-Content Disk:\Folder\users.txt
foreach ($user in $users) {
#Создаём папку в каталоге для хранения папок пользоватлей:
New-Item -path \\NetworkShare\ProfileFolder -name $user -type directory
#Получаем параметры доступа для этой папки в переменную $acl
$acl = get-acl "\\NetworkShare\ProfileFolder\$user"
#Удаляем все существующие права доступа на папку
$acl.SetAccessRuleProtection($true,$false)
#Даём полные права для группы Enterprise admins
$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("DOMAIN\Enterprise admins","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
#Даём полные права пользователю, для которого создаём папку
$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("DOMAIN\$user","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
#Важный момент! Применяем заданные права доступа
Set-Acl "\\NetworkShare\ProfileFolder\$user" $acl
<#Ввиду того, что у меня не получилось задать владельца папки, отличного от
того, от имени которого, запускется скрипт при помощи метода SetOwner для get-acl,
мне пришлось использовать icacls#>
icacls "\\NetworkShare\ProfileFolder\$user" /setowner "DOMAIN\$user" /T
#Здесь тоже самое, чтои выше, но уже для папки username.v2, которая используется Vista & 7
New-Item -path \\NetworkShare\ProfileFolder -name "$user.v2" -type directory
$acl = get-acl "\\NetworkShare\ProfileFolder\$user.v2"
$acl.SetAccessRuleProtection($true,$false)
$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("DOMAIN\Enterprise admins","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("DOMAIN\$user","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
Set-Acl "\\NetworkShare\ProfileFolder\$user.v2" $acl
icacls "\\NetworkShare\ProfileFolder\$user.v2" /setowner "DOMAIN\$user" /T
}
goro, net user Admin pass в политику автозагрузки компьютерас некоторых пор эта политика не работает, ее сам мелкософт посчитал не безопасной...
MS "отменил" политику смены паролей при помощи gpp, логон скрипты никто отменять не собирается.goro, net user Admin pass в политику автозагрузки компьютерас некоторых пор эта политика не работает, ее сам мелкософт посчитал не безопасной...
Поделитесь пжл, таким скриптомЭтим скриптом поделилась сама MS в соответствующей KB, в которой говорится о том, что возможность смены пароля при помощи GPP была убрана из политик.
а если это будет просто cmd в сценарии автозапуска компьютерада, но это еще более небезопасно, чем то, что отменил MS. Пароль хранится в открытом виде вообще внутри батника.
с текстом
echo off
net user user password
Должно сработать?
Ищу скрипт для отключения почтовых ящиков exchange у деактивированых учеток, более n-дней.создайте новую тему
Может кто поделиться?
Здесь размещаем скрипты. Обсуждение в других темах.Первая строка каждого поста должна быть представлена в следующем формате:Наименование скрипта#Язык программирования#автор
Get-ChildItem "C:\Users\*\AppData\Local\1C\1Cv82\*","C:\Users\*\AppData\Roaming\1C\1Cv82\*" | Where {$_.Name -as [guid]} |Remove-Item -Force -Recurse
######Настройки
#Указываем корень поиска. По умолчанию ищем во всем домене.
#Вместо $DomainDN указываем свой путь вида OU=Computers,OU=Accounts,DC=mydomain,DC=ru
$Srchroot = [ADSI]"LDAP://OU=Computers,OU=Accounts,DC=mydomain,DC=ru"
#Путь к лог-файлам
$LogPathLowSpace = "D:\work\log\usedSpace.log"
$LogPathClearSpace = "D:\work\log\clearedSpace.log"
Function Test-Host ($Name)
{
$ping = new-object System.Net.NetworkInformation.Ping
trap {Write-Verbose "Ошибка пинга"; $False; continue}
if ($ping.send($Name, 50).Status -eq "Success" ) { $True }
else { $False }
}
function Clear-TempFiles
{ param([string]$computername=$env:COMPUTERNAME)
$UsersDir = "\\$computername\C$\users"
$UserProfileTemp1 ="\AppData\Local\Temp"
$UserProfileTemp2 ="\AppData\Local\Microsoft\Windows\Temporary Internet Files"
$WindowsTemp = "\\$computername\C$\Windows\Temp"
$RecycleBin = "\\$computername\C$"+'\$Recycle.Bin'
$dirs = ls $UsersDir
foreach ($path in $dirs)
{
$temp1=$path.FullName+$UserProfileTemp1
$temp2=$path.FullName+$UserProfileTemp2
if((Test-Path $temp1) -and (Test-Path $temp2) ){
Write-host ("Clearing profile: "+$path+".....") -NoNewline
Remove-Item "$temp1\*" -Force -Recurse -Confirm:$false -ErrorAction SilentlyContinue
Remove-Item "$temp2\*" -Force -Recurse -Confirm:$false -ErrorAction SilentlyContinue
Write-Host "Done"
}
}
Write-Host ('Clearing C:\$Recycle.Bin.....') -NoNewline
Remove-Item "$RecycleBin\*" -Force -Recurse -Confirm:$false -ErrorAction SilentlyContinue
Write-Host "Done"
Write-Host ("Clearing C:\Windows\Temp:.....") -NoNewline
Remove-Item "$WindowsTemp\*" -Force -Recurse -Confirm:$false -ErrorAction SilentlyContinue
Write-Host "Done"
}
function Get-FreeSpace
{param ([string]$DnsHosName)
$driveC=Get-WmiObject Win32_LogicalDisk -ComputerName $DnsHosName| Where-Object {$_.DeviceID -eq "C:"}
$freespace=[int]($driveC.FreeSpace/1GB)
return $freespace
}
#====Обращение к Актив Директори=================
#Получаем имя домена
$DomainName = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$DomainDN = $DomainName.GetDirectoryEntry().distinguishedName
$DN=$DomainName.Name
#Получаем список компов в домене
$selector = New-Object system.DirectoryServices.DirectorySearcher
$Selector.SearchRoot = $Srchroot
$Selector.PageSize = 3000
$selector.Filter = '(objectClass=Computer)'
$selector.PropertiesToLoad.AddRange(@("name","dnshostname", "distinguishedName",
"canonicalName","lastLogonTimestamp"))
$Computers = $selector.FindAll()
#==================================================
""|Out-File -FilePath $LogPathLowSpace
""|Out-File -FilePath $LogPathClearSpace
foreach ($comp in $Computers)
{
$dnsname = $comp.Properties.get_item("dnshostname")
$CompName = $comp.Properties.get_item("name")
if(Test-Host $dnsname)
{
Write-Host "Scanning:"$CompName
$freespaceBeforClr = Get-FreeSpace -DnsHosName $dnsname
if ($freespaceBeforClr -le 10)
{
Write-Host ("Clearing: "+$CompName+" FreeSpace: "+$freespaceBeforClr)
Clear-TempFiles -computername $dnsname
$freespaceAfterClr = Get-FreeSpace -DnsHosName $dnsname
Write-Host ("Clearing: "+$CompName+" After clr: "+$freespaceAfterClr)
$clrResult = [string] ($CompName+$freespaceBeforClr+$freespaceAfterClr)
$clrResult|Out-File -FilePath $LogPathClearSpace -Append
if ($freespaceAfterClr -le 6)
{
$driveC=Get-WmiObject Win32_LogicalDisk -ComputerName $dnsname| Where-Object {$_.DeviceID -eq "C:"}
$totalspace=[int]($driveC.Size/1GB)
$result = [string] ($CompName+$freespaceAfterClr+$totalspace)
$result| Out-File -FilePath $LogPathLowSpace -Append
}
}
}
}
$CurrentDate = get-date -format dd.MM.yyyy
$DC_Name = "NAME_"
$NPath = "\\storage\BACKUP\"
$Path_Net_Drive = $NPath + $DC_Name + $CurrentDate
$StoreBackup_Period = 5
$limit = (Get-Date).AddDays(-$StoreBackup_Period)
$from = "admin@domain.net"
$to = "admin@domain.net"
$smtp = "mail.domain.local"
$sub = "NAME LAST BACKUP RESULT"
Function CheckPath ($Path) {
$Path_Exists = Test-Path -Path $Path
If ($Path_Exists -eq $False) {New-Item $Path -type directory}
}
Add-PSSnapin Windows.Serverbackup -ErrorAction SilentlyContinue
$policy = New-WBPolicy
$target = New-WBBackupTarget -NetworkPath $Path_Net_Drive
Add-WBBareMetalRecovery -Policy $policy
Add-WBSystemState -policy $policy
Add-WBVolume -Policy $policy -Volume (Get-WBVolume -CriticalVolumes)
Set-WBVssBackupOptions -policy $policy -VssFullBackup
Add-WBBackupTarget -Policy $policy -Target $target
CheckPath $Path_Net_Drive | Out-Null
Start-WBBackup -Policy $policy
if ((Get-WBSummary).LastBackupResultHR -eq 0) {
Get-ChildItem -Path $NPath -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
Get-ChildItem -Path $NPath -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
}
else {
Get-WBSummary > C:\SCRIPTS\summary.txt
Send-MailMessage -To $to -From $from -Subject $sub -Attachments C:\SCRIPTS\summary.txt -SmtpServer $smtp -DeliveryNotificationOption Never
}
$array = @()
$array2 = @()
$mailboxes = get-mailbox
$file = New-Item -itemtype file "C:\SCRIPTS\quotas.html" -Force
$mailalert=$false
Add-Content $file '<html><head>
<meta http-equiv="Content-Type" content="text/html;charset=windows-1251">
<title>System Status Report</title>
<style type="text/css">
<!--
BODY{background-color:#FFFFFF;}
TABLE{border-width: 1px;border-style: solid;border-color: black;}
TH{border-width: 1px;padding: 1px;border-style: solid;border-color: black;background-color:#1D92DC}
TD {border-width: 1px;padding: 2px;border-style: solid;border-color: black;background-color:#94BFE4}
TR {color:#000000;font-family:Tahoma;font-size:10pt;}
}
-->
</style>
<table>
<tr><th>mailbox: </th><th>state: </th></tr>
'
foreach ($line in $mailboxes) {
$user = $line.alias
$size2 = get-mailboxstatistics $user -erroraction silentlycontinue
if ($size2 -ne $null) {
$size = $size2.TotalItemSize.Value.ToMB()
}
$array += @(,($user,$size))
}
foreach ($line in $array) {
$user = $line[0]
$size = $line[1]
If ($user -notmatch 'DiscoverySearch') {
$quota2 = get-mailbox $user
$quotapsr = $quota2.ProhibitSendReceiveQuota
if ($quotapsr -ne "unlimited") {
$quotapsr = $quota2.ProhibitSendReceiveQuota.Value.ToMB()
if ($size -gt $quotapsr) {
$quotacheckpsr = "Over"
} else {
$quotacheckpsr = "Under"
}
} else {
$quotacheckpsr = "NoChecking"
}
$quotaiw = $quota2.IssueWarningQuota
if ($quotaiw -ne "unlimited") {
$quotaiw = $quota2.IssueWarningQuota.Value.ToMB()
if ($size -gt $quotaiw) {
$quotacheckiw = "Over"
} else {
$quotacheckiw = "Under"
}
} else {
$quotacheckiw = "NoChecking"
}
$quotaps = $quota2.ProhibitSendQuota
if ($quotaps -ne "unlimited") {
$quotaps = $quota2.ProhibitSendQuota.Value.ToMB()
if ($size -gt $quotaps) {
$quotacheckps = "Over"
} else {
$quotacheckps = "Under"
}
} else {
$quotacheckps = "NoChecking"
}
$array2 += @(,($user,$size,$quotacheckiw,$quotaiw,$quotacheckps,$quotaps,$quotacheckpsr,$quotapsr))
}
}
foreach ($line in $array2) {
if ($line[2] -eq "Over") {
$mbname=$line[0]
write-host "The mailbox for"$line[0]"is " -nonewline
write-host "OVER the Issue Warning Quota, " -ForegroundColor red -nonewline
Add-Content $file "<tr><td>$mbname</td><td style='background-color:red; color:Yellow;'><strong>OVER the Issue Warning Quota</strong></td></tr>"
$mailalert=$true
} else {
write-host "The mailbox for"$line[0]"is " -nonewline
write-host "UNDER the Issue Warning Quota, " -ForegroundColor green -nonewline
}
if ($line[4] -eq "Over") {
$mbname=$line[0]
write-host "OVER the Prohibit Send Quota," -ForegroundColor red -nonewline
Add-Content $file "<tr><td>$mbname</td><td style='background-color:red; color:Yellow;'><strong>OVER the Prohibit Send Quota</strong></td></tr>"
$mailalert=$true
} else {
write-host "UNDER the Prohibit Send Quota," -ForegroundColor green -nonewline
}
if ($line[6] -eq "Over") {
$mbname=$line[0]
write-host " and " -nonewline
write-host "OVER the Prohibit Send Receive Quota." -ForegroundColor red
Add-Content $file "<tr><td>$mbname</td><td style='background-color:red; color:Yellow;'><strong>OVER the Prohibit Send Receive Quota</strong></td></tr>"
$mailalert=$true
} else {
write-host " and " -nonewline
write-host "UNDER the Prohibit Send Receive Quota." -ForegroundColor green
}
}
if ($mailalert -eq $true) {
$html = Get-Content "C:\SCRIPTS\quotas.html" -raw
Send-MailMessage -smtpServer mail.domain.net -from 'alert@domain.net' -to 'admin@domain.net' -subject "Quotas" -body $html -Encoding UTF8 -BodyAsHTML
}
Param(
[string]$From = 'alert@domain.net'
[string]$To = 'admin@domain.net'
[string]$Server = 'mail.domain.local'
[switch]$email = $true
)
[int]$WarningLevel = 10
[int]$CriticalLevel = 20
[int]$ResultError = 0
[string]$computername=$env:computername
function Send-EmailMessage {
param([string]$EmailSubj=$Results, [string]$EmailBody=$Results)
$EmailMessage.Subject = $EmailSubj
$EmailMessage.Body = $EmailBody
$SMTPClient.Send( $EmailMessage )
}
$isHubTransportServer=(Test-Path "HKLM:\SOFTWARE\Microsoft\ExchangeServer\v15\HubTransportRole")
if ($isHubTransportServer) {
$MessagesQueued=get-wmiobject -query "select MessagesQueuedForDelivery from Win32_PerfFormattedData_MSExchangeTransportQueues_MSExchangeTransportQueues"
$Messages=$MessagesQueued.MessagesQueuedForDelivery
$MRes=[string]$messages
if ($Messages) {
if ($Messages -lt $WarningLevel) {
$Results = 'Все в порядке. Количество сообщений в очереди на сервере '+$computername+': ' +$MRes.remove(2)
}
if ($Messages -gt $WarningLevel) {
$ResultError=1
$Results = 'Я извиняюсь, но количество сообщений в очереди на сервере '+$computername+': ' +$MRes.remove(2)+ ' и мне это не по нраву...'
}
if ($Messages -gt $CriticalLevel) {
$ResultError=2
$Results = 'Алярм!!! Что-то пошло не так, и количество сообщений в очереди на сервере '+$computername+' достигло: ' +$MRes.remove(2)+ '. Это меня тревожит...'
}
}
Else {
$ResultError=1
$Results = 'Внимание! Очередь сообщений НЕДОСТУПНА на сервере ' +$computername
}
}
Else {
$Results='Exchange 2013 не установлен'
}
if ($email) {
$SMTPClient = New-Object Net.Mail.SMTPClient($Server, $Port)
if (($Username) -and ($Password)) { $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password) }
if ($SSL) { $SMTPClient.EnableSSL = $true }
$EmailMessage = New-Object System.Net.Mail.MailMessage
$EmailMessage.From = $From
$EmailMessage.To.Add( $To )
}
Switch ($ResultError) {
default {
write-host $Results
exit 0
}
1 {
write-host $Results
if ($email) { Send-EmailMessage }
exit 1
}
2 {
write-host $Results
if ($email) { Send-EmailMessage }
exit 2
}
}
#Server Name Prefix
$SRVPrefix="srv"
#Number of Computers
$NoC=99
#DaysDelay (do not look up for evets older then the delay)
$DaysDelay=1
#Name of Scheduled Task
$TaskName="Restart"
#Loop through the list of computers
$Tasks = 1..$NoC|%{
[int]$PC=100*$_/$NoC
$Srv="$SRVPrefix{0:d2}" -f $_
Write-Progress -Activity "Querying server $srv..." -status "$PC% Complete:" -PercentComplete $PC
if (Test-Connection -ComputerName $srv -Quiet -Count 1) {
Get-ScheduledTask -CimSession $Srv -TaskName RestartServer | select TaskName, State, PSComputerName, @{N="TriggersCount";E={$_.triggers.length}}, @{N="StartBoundary";E={$_.triggers[0].StartBoundary}}, @{N="DaysOfWeek";E={$a=$_.triggers[0].DaysOfWeek;$c="";do {$b=[math]::Truncate([math]::Log($a)/[math]::Log(2));$a-=[math]::Pow(2,$b);$c="$b"+$c} while ($a);$c}}
}
}
$Tasks | sort DaysOfWeek | ft -AutoSize