Подборка скриптов на PowerShell
Спасибо неизвестному автору за скрипт подключения к БД SQL
cls
Add-PSSnapin Quest.ActiveRoles.ADManagement
#--------------------------------------------
function changestring([string]$str)
{
$newstr=$str.remove(0,$str.indexof(':')+1)
$newstr=$newstr.TrimEnd(' ')
return $newstr
}
#----------------------------------------
$Mounth=@{'01'='Январь';'02'='Февраль';'03'='Март';'04'='Апрель';'05'='Май';'06'='Июнь';'07'='Июль';'08'='Август';'09'='Сентябрь';'10'='Октябрь';'11'='Ноябрь';'12'='Декабрь'}
Function CreateDate ([string]$Date)
{
$TMP=''
$TMP=$Date.remove(6)
$TmpDay = $TMP.remove(3)
$TmpMounth = $TMP.remove(0,4)
$TmpMounth = $mounth[$TmpMounth]
[string] $bdate = $Tmpmounth+$TmpDay
return $bdate
}
#-------------------------------------------------------------------
#---------------------------------------------------------------
# This script will execute a sql command and returns a formatted
# table of the result. The first parm can either be a query string
# or a path to a file that contains the query.
#
#---------------------------------------------------------------
#param(
# [string]$sqlFile = $(Throw "SQL command (or the full path/Filename to a .sql file) is required!"),
# [string]$server, #Optional parm to specify the server. Otherwise local is used.
# [string]$database, #Optional parm to specify the database to use in the connection
# [string]$userName, #Optional parm to specify the UserName/Password for the connection
# [string]$password #Optional parm to specify the UserName/Password for the connection
# )
[string]$sqlFile = 'SELECT tn, fam, im, ot, DATar FROM XBID WHERE (datau is null) and (tn<9000 by="" nbsp="" order="" p="" tn="">
[string]$server='Server-sc5' #Optional parm to specify the server. Otherwise local is used.
[string]$database='CIT_PERSONAL' #Optional parm to specify the database to use in the connection
[string]$userName = 'toolsuser' #Optional parm to specify the UserName/Password for the connection
[string]$password = 't00l$1qaz' #Optional parm to specify the UserName/Password for the connection
#---------------------------------------------------------------
# Determine if a sql command is given or the path to a file.
#
$command = $sqlFile.Trim();
if (Test-Path $command -pathType leaf)
{
#---------------------------------------------------------------
# Since a file path was given, pull the content as the sql command.
#
$command = Get-Content $command;
}
#---------------------------------------------------------------
# Create a connection object, if this cannot be create we must fail
#
$conn = New-Object System.Data.SqlClient.SqlConnection;
if (!$conn)
{
Throw "SqlConnection could not be created!";
return;
}
#---------------------------------------------------------------
# Default the server to local if one was not provided
#
if (!$server)
{
$server = "(local)";
}
$connString = "Server = $($server);";
#---------------------------------------------------------------
# Include the database in our connection string if one is given.
#
if ($database)
{
$connString = $connString + " Database = $($database);";
}
#---------------------------------------------------------------
# Base security on the existence of a username/password
#
if ($userName -and $password)
{
$connString = $connString + " User Id = $($userName); Password = $($password)";
}
else
{
$connString = $connString + " Integrated Security = True";
}
#---------------------------------------------------------------
# Now that we have built our connection string, attempt the connection.
#
$conn.ConnectionString = $connString;
$conn.Open();
if ($conn.State -eq 1)
{
$cmd = New-Object System.Data.SqlClient.SqlCommand $command, $conn;
if ($cmd)
{
$data = New-Object System.Data.SqlClient.SqlDataAdapter;
if ($data)
{
$ds = New-Object System.Data.DataSet;
if ($ds)
{
$data.SelectCommand = $cmd;
$data.Fill($ds) | Out-Null;
foreach ($table in $ds.Tables)
{
$table | Format-list | Out-file c:\temp\1.1
}
$ds.Dispose();
}
else
{
Write-Host "Failed creating the data set object!";
}
$data.Dispose();
}
else
{
Write-Host "Failed creating the data adapter object!";
}
$cmd.Dispose();
}
else
{
Write-Host "Failed creating the command object!";
}
$conn.Close();
}
else
{
Write-Host "Connection could not be opened!";
}
$conn.Dispose();
#------------------------------------------------------------------------
###################################################################
[Array]$test = Get-Content c:\temp\1.1
#$test.Length
$row = $test.Length
$users = New-Object 'object[,]' $test.Length,5
#$users.Gettype()
#[array]$users = @{}
$n=1
$i=0
do
{
$users[$I,0] = $test[$n+1]
$users[$I,1] = $test[$n+2]
$users[$I,2] = $test[$n+3]
$users[$I,3] = $test[$n+4]
$users[$I,4] = $test[$n+5]
$n=$n+6
$i=$i+1
if ($n -le $test.Length){$canexit = $false} else {$canexit = $true}
}until($canexit)
for ($j=0; $j -le $i; $j++){
[string]$tabnumber = changestring $users[$j,0]
$tabnumber = $tabnumber.TrimStart(' ')
[string]$lastname = changestring $users[$j,1]
[string]$FirstName = changestring $users[$j,2]
[string]$secondname = changestring $users[$j,3]
[string]$birthday = changestring $users[$j,4]
$Birthday = createdate $birthday
$displayname = $lastname.trimstart(' ')+' '+$FirstName.trimstart(' ')+' '+$secondname.trimstart(' ')
Get-QADUser -DisplayName $displayname | Set-QADUser -ObjectAttributes @{UserEmpBirsday = $birthday; EmployeeNumber = $tabnumber }
#Get-QADUser -ObjectAttributes @{employeeNumber = $tabnumber} | Select-Object -Property DisplayName,USerEmpBirsday,EmployeeNumber
}
cls
Add-PSSnapin Quest.ActiveRoles.ADManagement
#--------------------------------------------
function changestring([string]$str)
{
$newstr=$str.remove(0,$str.indexof(':')+1)
$newstr=$newstr.TrimEnd(' ')
return $newstr
}
#----------------------------------------
$Mounth=@{'01'='Январь';'02'='Февраль';'03'='Март';'04'='Апрель';'05'='Май';'06'='Июнь';'07'='Июль';'08'='Август';'09'='Сентябрь';'10'='Октябрь';'11'='Ноябрь';'12'='Декабрь'}
Function CreateDate ([string]$Date)
{
$TMP=''
$TMP=$Date.remove(6)
$TmpDay = $TMP.remove(3)
$TmpMounth = $TMP.remove(0,4)
$TmpMounth = $mounth[$TmpMounth]
[string] $bdate = $Tmpmounth+$TmpDay
return $bdate
}
#-------------------------------------------------------------------
#---------------------------------------------------------------
# This script will execute a sql command and returns a formatted
# table of the result. The first parm can either be a query string
# or a path to a file that contains the query.
#
#---------------------------------------------------------------
#param(
# [string]$sqlFile = $(Throw "SQL command (or the full path/Filename to a .sql file) is required!"),
# [string]$server, #Optional parm to specify the server. Otherwise local is used.
# [string]$database, #Optional parm to specify the database to use in the connection
# [string]$userName, #Optional parm to specify the UserName/Password for the connection
# [string]$password #Optional parm to specify the UserName/Password for the connection
# )
[string]$sqlFile = 'SELECT tn, fam, im, ot, DATar FROM XBID WHERE (datau is null) and (tn<9000 by="" nbsp="" order="" p="" tn="">
[string]$server='Server-sc5' #Optional parm to specify the server. Otherwise local is used.
[string]$database='CIT_PERSONAL' #Optional parm to specify the database to use in the connection
[string]$userName = 'toolsuser' #Optional parm to specify the UserName/Password for the connection
[string]$password = 't00l$1qaz' #Optional parm to specify the UserName/Password for the connection
#---------------------------------------------------------------
# Determine if a sql command is given or the path to a file.
#
$command = $sqlFile.Trim();
if (Test-Path $command -pathType leaf)
{
#---------------------------------------------------------------
# Since a file path was given, pull the content as the sql command.
#
$command = Get-Content $command;
}
#---------------------------------------------------------------
# Create a connection object, if this cannot be create we must fail
#
$conn = New-Object System.Data.SqlClient.SqlConnection;
if (!$conn)
{
Throw "SqlConnection could not be created!";
return;
}
#---------------------------------------------------------------
# Default the server to local if one was not provided
#
if (!$server)
{
$server = "(local)";
}
$connString = "Server = $($server);";
#---------------------------------------------------------------
# Include the database in our connection string if one is given.
#
if ($database)
{
$connString = $connString + " Database = $($database);";
}
#---------------------------------------------------------------
# Base security on the existence of a username/password
#
if ($userName -and $password)
{
$connString = $connString + " User Id = $($userName); Password = $($password)";
}
else
{
$connString = $connString + " Integrated Security = True";
}
#---------------------------------------------------------------
# Now that we have built our connection string, attempt the connection.
#
$conn.ConnectionString = $connString;
$conn.Open();
if ($conn.State -eq 1)
{
$cmd = New-Object System.Data.SqlClient.SqlCommand $command, $conn;
if ($cmd)
{
$data = New-Object System.Data.SqlClient.SqlDataAdapter;
if ($data)
{
$ds = New-Object System.Data.DataSet;
if ($ds)
{
$data.SelectCommand = $cmd;
$data.Fill($ds) | Out-Null;
foreach ($table in $ds.Tables)
{
$table | Format-list | Out-file c:\temp\1.1
}
$ds.Dispose();
}
else
{
Write-Host "Failed creating the data set object!";
}
$data.Dispose();
}
else
{
Write-Host "Failed creating the data adapter object!";
}
$cmd.Dispose();
}
else
{
Write-Host "Failed creating the command object!";
}
$conn.Close();
}
else
{
Write-Host "Connection could not be opened!";
}
$conn.Dispose();
#------------------------------------------------------------------------
###################################################################
[Array]$test = Get-Content c:\temp\1.1
#$test.Length
$row = $test.Length
$users = New-Object 'object[,]' $test.Length,5
#$users.Gettype()
#[array]$users = @{}
$n=1
$i=0
do
{
$users[$I,0] = $test[$n+1]
$users[$I,1] = $test[$n+2]
$users[$I,2] = $test[$n+3]
$users[$I,3] = $test[$n+4]
$users[$I,4] = $test[$n+5]
$n=$n+6
$i=$i+1
if ($n -le $test.Length){$canexit = $false} else {$canexit = $true}
}until($canexit)
for ($j=0; $j -le $i; $j++){
[string]$tabnumber = changestring $users[$j,0]
$tabnumber = $tabnumber.TrimStart(' ')
[string]$lastname = changestring $users[$j,1]
[string]$FirstName = changestring $users[$j,2]
[string]$secondname = changestring $users[$j,3]
[string]$birthday = changestring $users[$j,4]
$Birthday = createdate $birthday
$displayname = $lastname.trimstart(' ')+' '+$FirstName.trimstart(' ')+' '+$secondname.trimstart(' ')
Get-QADUser -DisplayName $displayname | Set-QADUser -ObjectAttributes @{UserEmpBirsday = $birthday; EmployeeNumber = $tabnumber }
#Get-QADUser -ObjectAttributes @{employeeNumber = $tabnumber} | Select-Object -Property DisplayName,USerEmpBirsday,EmployeeNumber
}
PARAM ([string]$P)
$date = get-Date
echo "$date $p" >> C:\scr\logparam
cls
Add-PSSnapin Quest.ActiveRoles.ADManagement
#$P = Get-Content 'H:\NewUsers\new_pip.log'
#Транслитерация
Function Transliteral ([String]$InStr)
{
$ConvRules=@{"а"="a";"б"="b";"в"="v";"г"="g";"д"="d";"е"="e";"ё"="e";"ж"="zh";"з"="z";"и"="i";"й"="y";"к"="k";"л"="l";"м"="m";"н"="n";"о"="o";"п"="p";"р"="r";"с"="s";"т"="t";"у"="y";"ф"="f";"х"="h";"ц"="ts";"ч"="ch";"ш"="sh";"щ"="shch";"ъ"="";"ы"="i";"ь"="";"э"="e";"ю"="u";"я"="ya"};
$s = $InStr
for ($i=0; $i -le $s.Length-1; $i++)
{
$ch = $ConvRules[$s[$i].ToString().ToLower()]
if ( $s[$i].ToString().ToUpper() -ceq $s[$i].ToString() ) { $ch=$ch.Replace($ch[0],$ch[0].ToString().ToUpper()); }
$trn=$trn+$ch;
}
$trn
}
#Список орг единиц
#Получаем полный список организационных едениц
Function GetOU ()
{
Get-QADObject -Type organizationalUnit | Format-Wide -Column 1 | Out-File C:\Temp\temp.txt
#Удаляем пустые сроки в файле
gc c:\Temp\temp.txt | where {$_ -ne ""} > c:\Temp\temp1.txt
$OUList = Get-Content c:\Temp\temp1.txt
return $OUList
}
#Получаем полное доменное имя
function TakeDN ([string]$N)
{
$Nn = $N.TrimEnd(1,' ')
# Получаем полное имя выбранного отдела
$TempDN = ''
[string]$TempDN = Get-QADObject -Type 'organizationalUnit' -Name $Nn | Select-Object -Property DN
$tempDN=$tempDN.Remove(0,5)
$tempDN=$tempDN.TrimEnd('}')
return [string]$tempDN
}
Function GetOU ()
{
$TempOU = Get-QADObject -Type organizationalUnit | Select-Object -Property Name
foreach($item in $TempOU)
{
$temp = ''
[string]$temp=$item
$temp=$temp.Remove(0,7)
$temp=$temp.TrimEnd('}')
[array]$Oulist = $Oulist + $temp
}
return $OUList
}
function SearchOU ( [string] $UD2 )
{
# Ищем совпадения в списке и записываем их в отдельны массив
$ListOfOU2=@()
$ArOu2 = GetOU
$UD2 = $UD2
foreach ($item in $ArOu2)
{
if (($item -eq $ud2))
{
[Array] $ListOfOU2=$ListOfOU2 + $item
}
}
return $ListOfOU2
}
# Выбираем OU куда будем добалять пользователя
# Споймала глюк при отмене ввода подразделения вместо выхода из скрипта, он завел пользователя в первом подразделении из списка
function ParentFolder ( [string] $UD)
{
do
{
$can_exit=$true
#Ишем совпадения в списке
[Array] $ListOfOU = SearchOU $UD
switch ($ListOfOU.count) {
$null{
$body1 = "No of dapartment create user int tempusers, please check " + $ud
$DN = TakeDN 'TempUsers'
$DPN = 'TempUsers'
$can_exit = $true
}
1{ # Если совпадение одно возвращаем результат
$DN = TakeDN $ListOfOU[0]
$DPN = $ListOfOU[0]
$can_exit = $true
}
default {
$body1 = "Many of case in dapartment create user int tempusers, please check " + $UD
$DN = TakeDN 'TempUsers'
$DPN = 'TempUsers'
$can_exit = $true
}
}
}until($can_exit)
return $DN, $DPN
}
#------------------------------------------------------------------------------
#Основное тело
#Проверить что параметры не пустые
#$smt
$p
if ($P -like '*error*')
{
Write-Host 'error'
send-mailmessage -from "PowerShell@bank.local" -to "Admin @bank.local" -subject "Error work whit triger" -body "Error Resive Data From KominTeh Call Kalugin_ds" -priority High -smtpServer Server
break
}
foreach ($item in $p){
echo "Start Create user" >> C:\scr\logparam
$str = ''
[array]$str = $item.split('#')
$str
# $tmp = $str[0].Remove(0,2);
$UserName = [string]$str[2]
$UserFname = [string]$str[3]
$UserLastname = [string]$str[1]
echo "$username $userFname $userLastName" >> C:\scr\logparam
switch ($trigger){
default {
#Создаем логин пользователя
$Tname = Transliteral $UserName
$TFname = Transliteral $UserFname
$TLName = Transliteral $UserLastname
$UserLogin = $TLName+'_'+$Tname.substring(0,1)+$TFName.substring(0,1)
echo "$UserLogin" >> C:\scr\logparam
$UserPassw = 'Temp$#Passwod$Tohcange'
$UserW = [string]$str[5]
$UserDepartment = [string]$str[6]
$MailDomain = '@sab.donetsk.ua'
$TabNamber = [string]$str[4]
$UserMail = $UserLogin+$MailDomain;
$UserCompany = 'ПАО "БАНК"'
$UserPrincipalName = $UserLogin+'@bank.local'
#Создаем фильт поиска
# Получаем имя отдела и полное доменное имя оушки
$res = ParentFolder $UserDepartment
[string]$distinguishedName = $res[0]
[string]$UserDepartment =$res[1]
echo "$distinguishedName $UserDepartment" >> C:\scr\logparam
$UserDepartment=$UserDepartment.TrimEnd(1,' ')
$distinguishedName=$distinguishedName.TrimEnd(1,' ')
#Отрезаем инициал
$UserFname2 = $UserFname
$UserFname2 = $UserFname2.Substring(0,1)
#Генерируем CN и Отображаемое имя
$CN=$UserName+" "+$UserFname2+". "+$UserLastname
$DisplayName = $UserLastname+" "+$userName+" "+$UserFName
$nl = [System.Environment]::NewLine
$Subject = 'Create new User: ' + $DisplayName + ' ' + $UserLogin
$body = $body1+$nl+'User parametrs: ' + $DisplayName +$nl+ ' Отдел: ' + $UserDepartment +$nl+ ' Должность: '+ $UserW +$nl+' Логин и пароль, пароль необходимо изменить: '+ $UserLogin+'/'+$UserPassw +$nl+' Почтовый адрес, изменить если необходимо: ' + $UserMail +$nl+ 'Табельный номер'+$TabNamber + $nl+$distinguishedName + $nl + 'Учетная запись почты (необходимо переместить из Contacts' + $UserMail + $nl + 'Также не забудьте включить учетную запись'
#Добавляем пользователя в домен
$result = new-QADUser -FirstName $UserName -LastName $UserLastname -Initials $UserFname2 -DisplayName $DisplayName -Name $CN -SamAccountName $UserLogin -UserPrincipalName $UserPrincipalName -UserPassword $UserPassw -ParentContainer $distinguishedName -Email $UserMail -ObjectAttributes @{department = $UserDepartment; company = $UserCompany; title = $UserW; employeeNumber = $tabnumber} | Disable-QADUser
echo "$result" >> C:\scr\logparam
$CN=$UserLastname+" "+$UserName+" "+$UserFname
Send-MailMessage -from "PowerShell" -to "Chistilina_tn " -subject $Subject -body $body -priority High -smtpServer 91.0.0.35 -Encoding ([System.Text.Encoding]::UTF8)
}
}
}
$date = get-Date
echo "$date $p" >> C:\scr\logparam
cls
Add-PSSnapin Quest.ActiveRoles.ADManagement
#$P = Get-Content 'H:\NewUsers\new_pip.log'
#Транслитерация
Function Transliteral ([String]$InStr)
{
$ConvRules=@{"а"="a";"б"="b";"в"="v";"г"="g";"д"="d";"е"="e";"ё"="e";"ж"="zh";"з"="z";"и"="i";"й"="y";"к"="k";"л"="l";"м"="m";"н"="n";"о"="o";"п"="p";"р"="r";"с"="s";"т"="t";"у"="y";"ф"="f";"х"="h";"ц"="ts";"ч"="ch";"ш"="sh";"щ"="shch";"ъ"="";"ы"="i";"ь"="";"э"="e";"ю"="u";"я"="ya"};
$s = $InStr
for ($i=0; $i -le $s.Length-1; $i++)
{
$ch = $ConvRules[$s[$i].ToString().ToLower()]
if ( $s[$i].ToString().ToUpper() -ceq $s[$i].ToString() ) { $ch=$ch.Replace($ch[0],$ch[0].ToString().ToUpper()); }
$trn=$trn+$ch;
}
$trn
}
#Список орг единиц
#Получаем полный список организационных едениц
Function GetOU ()
{
Get-QADObject -Type organizationalUnit | Format-Wide -Column 1 | Out-File C:\Temp\temp.txt
#Удаляем пустые сроки в файле
gc c:\Temp\temp.txt | where {$_ -ne ""} > c:\Temp\temp1.txt
$OUList = Get-Content c:\Temp\temp1.txt
return $OUList
}
#Получаем полное доменное имя
function TakeDN ([string]$N)
{
$Nn = $N.TrimEnd(1,' ')
# Получаем полное имя выбранного отдела
$TempDN = ''
[string]$TempDN = Get-QADObject -Type 'organizationalUnit' -Name $Nn | Select-Object -Property DN
$tempDN=$tempDN.Remove(0,5)
$tempDN=$tempDN.TrimEnd('}')
return [string]$tempDN
}
Function GetOU ()
{
$TempOU = Get-QADObject -Type organizationalUnit | Select-Object -Property Name
foreach($item in $TempOU)
{
$temp = ''
[string]$temp=$item
$temp=$temp.Remove(0,7)
$temp=$temp.TrimEnd('}')
[array]$Oulist = $Oulist + $temp
}
return $OUList
}
function SearchOU ( [string] $UD2 )
{
# Ищем совпадения в списке и записываем их в отдельны массив
$ListOfOU2=@()
$ArOu2 = GetOU
$UD2 = $UD2
foreach ($item in $ArOu2)
{
if (($item -eq $ud2))
{
[Array] $ListOfOU2=$ListOfOU2 + $item
}
}
return $ListOfOU2
}
# Выбираем OU куда будем добалять пользователя
# Споймала глюк при отмене ввода подразделения вместо выхода из скрипта, он завел пользователя в первом подразделении из списка
function ParentFolder ( [string] $UD)
{
do
{
$can_exit=$true
#Ишем совпадения в списке
[Array] $ListOfOU = SearchOU $UD
switch ($ListOfOU.count) {
$null{
$body1 = "No of dapartment create user int tempusers, please check " + $ud
$DN = TakeDN 'TempUsers'
$DPN = 'TempUsers'
$can_exit = $true
}
1{ # Если совпадение одно возвращаем результат
$DN = TakeDN $ListOfOU[0]
$DPN = $ListOfOU[0]
$can_exit = $true
}
default {
$body1 = "Many of case in dapartment create user int tempusers, please check " + $UD
$DN = TakeDN 'TempUsers'
$DPN = 'TempUsers'
$can_exit = $true
}
}
}until($can_exit)
return $DN, $DPN
}
#------------------------------------------------------------------------------
#Основное тело
#Проверить что параметры не пустые
#$smt
$p
if ($P -like '*error*')
{
Write-Host 'error'
send-mailmessage -from "PowerShell@bank.local
break
}
foreach ($item in $p){
echo "Start Create user" >> C:\scr\logparam
$str = ''
[array]$str = $item.split('#')
$str
# $tmp = $str[0].Remove(0,2);
$UserName = [string]$str[2]
$UserFname = [string]$str[3]
$UserLastname = [string]$str[1]
echo "$username $userFname $userLastName" >> C:\scr\logparam
switch ($trigger){
default {
#Создаем логин пользователя
$Tname = Transliteral $UserName
$TFname = Transliteral $UserFname
$TLName = Transliteral $UserLastname
$UserLogin = $TLName+'_'+$Tname.substring(0,1)+$TFName.substring(0,1)
echo "$UserLogin" >> C:\scr\logparam
$UserPassw = 'Temp$#Passwod$Tohcange'
$UserW = [string]$str[5]
$UserDepartment = [string]$str[6]
$MailDomain = '@sab.donetsk.ua'
$TabNamber = [string]$str[4]
$UserMail = $UserLogin+$MailDomain;
$UserCompany = 'ПАО "БАНК"'
$UserPrincipalName = $UserLogin+'@bank.local'
#Создаем фильт поиска
# Получаем имя отдела и полное доменное имя оушки
$res = ParentFolder $UserDepartment
[string]$distinguishedName = $res[0]
[string]$UserDepartment =$res[1]
echo "$distinguishedName $UserDepartment" >> C:\scr\logparam
$UserDepartment=$UserDepartment.TrimEnd(1,' ')
$distinguishedName=$distinguishedName.TrimEnd(1,' ')
#Отрезаем инициал
$UserFname2 = $UserFname
$UserFname2 = $UserFname2.Substring(0,1)
#Генерируем CN и Отображаемое имя
$CN=$UserName+" "+$UserFname2+". "+$UserLastname
$DisplayName = $UserLastname+" "+$userName+" "+$UserFName
$nl = [System.Environment]::NewLine
$Subject = 'Create new User: ' + $DisplayName + ' ' + $UserLogin
$body = $body1+$nl+'User parametrs: ' + $DisplayName +$nl+ ' Отдел: ' + $UserDepartment +$nl+ ' Должность: '+ $UserW +$nl+' Логин и пароль, пароль необходимо изменить: '+ $UserLogin+'/'+$UserPassw +$nl+' Почтовый адрес, изменить если необходимо: ' + $UserMail +$nl+ 'Табельный номер'+$TabNamber + $nl+$distinguishedName + $nl + 'Учетная запись почты (необходимо переместить из Contacts' + $UserMail + $nl + 'Также не забудьте включить учетную запись'
#Добавляем пользователя в домен
$result = new-QADUser -FirstName $UserName -LastName $UserLastname -Initials $UserFname2 -DisplayName $DisplayName -Name $CN -SamAccountName $UserLogin -UserPrincipalName $UserPrincipalName -UserPassword $UserPassw -ParentContainer $distinguishedName -Email $UserMail -ObjectAttributes @{department = $UserDepartment; company = $UserCompany; title = $UserW; employeeNumber = $tabnumber} | Disable-QADUser
echo "$result" >> C:\scr\logparam
$CN=$UserLastname+" "+$UserName+" "+$UserFname
Send-MailMessage -from "PowerShell
}
}
}
cls
$users = get-qaduser -SearchRoot "bank.local/Usual Users/Департамент автоматизации"
cls
foreach ($user in $users)
{
$displayname = $user.displayname
$sip = $user.userPrincipalName
#$string = 'Enable-CsUser -Identity "' + $displayname + '" ' + '-RegistrarPool server7.bank.local -SipAddress "' + 'sip:' +$sip+'"'
$string = 'Set-CsPersistentChatRoom -Identity "Автоматизация общая комната" -members @{Add="sip:'+ $sip +'"}'
Write-Host $string
}
$users = get-qaduser -SearchRoot "bank.local/Usual Users/Департамент автоматизации"
cls
foreach ($user in $users)
{
$displayname = $user.displayname
$sip = $user.userPrincipalName
#$string = 'Enable-CsUser -Identity "' + $displayname + '" ' + '-RegistrarPool server7.bank.local -SipAddress "' + 'sip:' +$sip+'"'
$string = 'Set-CsPersistentChatRoom -Identity "Автоматизация общая комната" -members @{Add="sip:'+ $sip +'"}'
Write-Host $string
}
$TempDN = Get-QADObject -Type 'organizationalUnit'
#Obhodim spisok vseh podrazdeleniy
Foreach ($DN in $TempDN)
{
$DN
#Poluchaem dolgnsot Nachalnik departementa dly vseh podrazdeleniy
$DM = Get-QADUser -SearchScope OneLevel -SearchRoot $DN -Title '*начальник департамента*'
#Esli est nachalnik
if ($DM -ne $null)
{
$mes = 'Начальник департамента существует ' + $DN.DN
Write-Host $mes
#Zami
get-qaduser -SearchScope OneLevel -SearchRoot $DN -Title '*начальника департамента*' | Set-QADUser -Manager $DM
#Polychaem spisok dochernih podrazdeleniy
$TempOU = Get-QADObject -Type 'organizationalUnit' -SearchRoot $DN.DN
#Dly kagdogo dochernego podrazdeleniya ischem nachalnika
FOReach ($ou in $tempou)
{
$OM = get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN -Title '*начальник отдела*'
#Esli est nach otdela zapolnayem orgstruktury inache ishem zama
if($OM -ne $null)
{
$mes = 'Начальник отдела существует ' + $OU.DN
Write-Host $mes
get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN | Set-QADUser -Manager $OM
get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN -Title '*начальник отдела*' | Set-QADUSer -Manager $DM
}
Else
{
#ishem zama
$ZOM = get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN -Title '*начальника отдела*'
if($ZOM -ne $null)
{
$mes = 'Зам. начальника отдела существует ' + $OU.DN
Write-Host $mes
get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN | Set-QADUser -Manager $ZOM
get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN -Title '*начальника отдела*' | Set-QADUser -Manager $DM
}
}
}
}
Else
{
}
}
#Obhodim spisok vseh podrazdeleniy
Foreach ($DN in $TempDN)
{
$DN
#Poluchaem dolgnsot Nachalnik departementa dly vseh podrazdeleniy
$DM = Get-QADUser -SearchScope OneLevel -SearchRoot $DN -Title '*начальник департамента*'
#Esli est nachalnik
if ($DM -ne $null)
{
$mes = 'Начальник департамента существует ' + $DN.DN
Write-Host $mes
#Zami
get-qaduser -SearchScope OneLevel -SearchRoot $DN -Title '*начальника департамента*' | Set-QADUser -Manager $DM
#Polychaem spisok dochernih podrazdeleniy
$TempOU = Get-QADObject -Type 'organizationalUnit' -SearchRoot $DN.DN
#Dly kagdogo dochernego podrazdeleniya ischem nachalnika
FOReach ($ou in $tempou)
{
$OM = get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN -Title '*начальник отдела*'
#Esli est nach otdela zapolnayem orgstruktury inache ishem zama
if($OM -ne $null)
{
$mes = 'Начальник отдела существует ' + $OU.DN
Write-Host $mes
get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN | Set-QADUser -Manager $OM
get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN -Title '*начальник отдела*' | Set-QADUSer -Manager $DM
}
Else
{
#ishem zama
$ZOM = get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN -Title '*начальника отдела*'
if($ZOM -ne $null)
{
$mes = 'Зам. начальника отдела существует ' + $OU.DN
Write-Host $mes
get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN | Set-QADUser -Manager $ZOM
get-qaduser -SearchScope OneLevel -SearchRoot $OU.DN -Title '*начальника отдела*' | Set-QADUser -Manager $DM
}
}
}
}
Else
{
}
}
cls
$Days = "-7"
$Today = "-1"
$CurrentDate = Get-Date
#1.Вычисляем возраст файлов
$OldDate = $CurrentDate.AddDays($Days)
#2.Файлы за сегодня
$Day = $CurrentDate.AddDays($Today)
function Arhive ([string]$backup, [string]$path)
{
#3.Копируем файлы которые созданы сегодня
#Get-ChildItem $Path | Where-Object {$_.LastWriteTime -gt $Day} | Copy-Item -Destination $backup -Force -Recurse
Get-ChildItem $Path | Copy-Item -Destination $backup -Force -Recurse
#4.Удаляем файлы старше чем семь дней назад
#Get-ChildItem $backup | Where-Object { $_.LastWriteTime -lt $OldDate } | Remove-Item
Get-ChildItem $backup -Recurse | Where-Object { $_.LastWriteTime -lt $OldDate } | Remove-Item
}
Arhive "\\Backup\K\" "G:\"
$Days = "-7"
$Today = "-1"
$CurrentDate = Get-Date
#1.Вычисляем возраст файлов
$OldDate = $CurrentDate.AddDays($Days)
#2.Файлы за сегодня
$Day = $CurrentDate.AddDays($Today)
function Arhive ([string]$backup, [string]$path)
{
#3.Копируем файлы которые созданы сегодня
#Get-ChildItem $Path | Where-Object {$_.LastWriteTime -gt $Day} | Copy-Item -Destination $backup -Force -Recurse
Get-ChildItem $Path | Copy-Item -Destination $backup -Force -Recurse
#4.Удаляем файлы старше чем семь дней назад
#Get-ChildItem $backup | Where-Object { $_.LastWriteTime -lt $OldDate } | Remove-Item
Get-ChildItem $backup -Recurse | Where-Object { $_.LastWriteTime -lt $OldDate } | Remove-Item
}
Arhive "\\Backup\K\" "G:\"
cls
$strComputer = "."
$colItems = get-wmiobject -class "Win32_Battery" -namespace "root\CIMV2" -computername $strComputer
$EstimatedChargeRemaining = new-object object[] 2
$UPS = New-Object "object[,]" 2,7
$i=0
$username = "bank\user"
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
#$serverNameOrIp = "192.168.1.1"
#Restart-Computer -ComputerName $serverNameOrIp `
# -Authentication default `
# -Credential $cred
foreach ($objItem in $colItems) {
$date = Get-Date
$file = 'c:\script\upslog'+$i+'.log'
if ($UPS[$i,2] -lt 100) {
Add-Content $file $date
$UPS[$i,0] = $objItem.DeviceID
$Temp = "Device ID: " + $UPS[$i,0]
Add-Content $file $Temp
$UPS[$i,1] = $objItem.BatteryStatus
$Temp = "Battery Status: " + $UPS[$i,1]
Add-Content $file $Temp
$UPS[$i,2] = $objItem.EstimatedChargeRemaining
$Temp = "Estimated Charge Remaining: " + $UPS[$i,2]
$Temp
$EstimatedChargeRemaining[$i] = $UPS[$i,2]
$EstimatedChargeRemaining[$i]
Add-Content $file $Temp
$UPS[$i,3] = $objItem.EstimatedRunTime
$Temp = "Estimated Run Time: " + $UPS[$i,3]
Add-Content $file $Temp
$UPS[$i,4] = $objItem.Status
$Temp = "Status: " + $UPS[$i,4]
Add-Content $file $Temp
$UPS[$i,5] = $objItem.SystemName
$Temp = "System Name: " + $UPS[$i,5]
$SystemName = $UPS[$i,5]
Add-Content $file $Temp
}
# write-host "Availability: " $objItem.Availability
# write-host "Battery Recharge Time: " $objItem.BatteryRechargeTime
# write-host "Battery Status: " $objItem.BatteryStatus
# write-host "Caption: " $objItem.Caption
# write-host "Chemistry: " $objItem.Chemistry
# write-host "Configuration Manager Error Code: " $objItem.ConfigManagerErrorCode
# write-host "Configuration Manager User Configuration: " $objItem.ConfigManagerUserConfig
# write-host "Creation Class Name: " $objItem.CreationClassName
# write-host "Description: " $objItem.Description
# write-host "Design Capacity: " $objItem.DesignCapacity
# Designed voltage of the battery in millivolts. If this attribute is not supported, enter 0.
# write-host "Design Voltage: " $objItem.DesignVoltage
# write-host "Device ID: " $objItem.DeviceID
# write-host "Error Cleared: " $objItem.ErrorCleared
# write-host "Error Description: " $objItem.ErrorDescription
# write-host "Estimated Charge Remaining: " $objItem.EstimatedChargeRemaining
# write-host "Estimated Run Time: " $objItem.EstimatedRunTime
# write-host "Expected Battery Life: " $objItem.ExpectedBatteryLife
# write-host "Expected Life: " $objItem.ExpectedLife
# write-host "Full Charge Capacity: " $objItem.FullChargeCapacity
# write-host "Installation Date: " $objItem.InstallDate
# write-host "Last Error Code: " $objItem.LastErrorCode
# write-host "Maximum Recharge Time: " $objItem.MaxRechargeTime
# write-host "Name: " $objItem.Name
# write-host "PNP Device ID: " $objItem.PNPDeviceID
# write-host "Power Management Capabilities: " $objItem.PowerManagementCapabilities
# write-host "Power Management Supported: " $objItem.PowerManagementSupported
# write-host "Smart Battery Version: " $objItem.SmartBatteryVersion
# write-host "Status: " $objItem.Status
# write-host "Status Information: " $objItem.StatusInfo
# write-host "System Creation Class Name: " $objItem.SystemCreationClassName
# write-host "System Name: " $objItem.SystemName
# write-host "Time On Battery: " $objItem.TimeOnBattery
# write-host "Time To Full Charge: " $objItem.TimeToFullCharge
$i=$i+1
}
#Общий лог
$file = "c:\script\upslog.log"
#Проверяем уровень разрядки и отправляем сообщения. Тушим сервера
if ($i=2){
#Если скрипт используется для контроля двух УПС
if (([int]$EstimatedChargeRemaining[0]+[int]$EstimatedChargeRemaining[1] -le 95) -and ($UPS[0,1] -eq 1) -and ($ups[1,1] -eq 1))
{
$sum = [int]$EstimatedChargeRemaining[0]+[int]$EstimatedChargeRemaining[1]
$date = Get-Date
Add-Content $file 'Sum Charege is'
Add-Content $file $sum
$subject=""
$subject = "Power failed on server " + $SystemName + " at " + $date
$body=""
$body = "Current charge on ups1 is " + $EstimatedChargeRemaining[0] + ". Current charge on ups2 is " + $EstimatedChargeRemaining[1]+ "."
$body = $body + " Estimate minutes of the time to battery charge depletion is " + $UPS[0,3] + " on ups1 and " + $UPS[1,3] + " on ups2."
$body = $body + " Shutdown Server7"
Send-MailMessage -From "PowerShell" -To "Admin " -Subject $subject -Body $body -priority High -smtpServer 91.0.0.35 -Encoding ([System.Text.Encoding]::UTF8)
Stop-Computer -Credential $cred -ComputerName server7.bank.local -Force
#Кол-во серверов для выключения не ограничено
}
}else
{
# Если скрипт используется для контроля одного УПС
if ([int]$EstimatedChargeRemaining[0] -le 95)
{
$date = Get-Date
Add-Content $file 'Sum Charege is'
Add-Content $file $EstimatedChargeRemaining[0]
$subject=""
$subject = "Power failed on server " + $SystemName + " at " + $date
$body=""
$body = "Current charge on ups is " + $EstimatedChargeRemaining[0]
$body = $body + " Estimate minutes of the time to battery charge depletion is " + $UPS[0,3]
$body = $body + " Shutdown Server7"
Send-MailMessage -From "PowerShell" -To "Admin " -Subject $subject -Body $body -priority High -smtpServer 91.0.0.35 -Encoding ([System.Text.Encoding]::UTF8)
Stop-Computer -Credential $cred -ComputerName server7.bank.local -Force
#Кол-во серверов для выключения не ограничено
}
}
#--------------------------------------------------------------------------------------------------------------------------------
#Фиксируем время віключения и включения єлектричества
If (($UPS[0,1] -eq 1) -and -not(Test-Path c:\script\batterystatus1.log))
{
$body=""
$subject = ""
$subject="Power failed on server " + $SystemName + " at " + $date + " on UPS1"
$body = "Power failed on server " + $SystemName + " at " + $date + " on UPS1 " + $objItem.DeviceID
Send-MailMessage -From "PowerShell" -To "Admin " -Subject $subject -Body $body -priority High -smtpServer 91.0.0.35 -Encoding ([System.Text.Encoding]::UTF8)
$UPS[0,1] | Out-File c:\script\batterystatus1.log
Add-Content $file $body
}
If (($UPS[1,1] -eq 1) -and -not(Test-Path c:\script\batterystatus2.log))
{
$body=""
$subject = ""
$subject="Power failed on server " + $SystemName + " at " + $date + " on UPS2"
$body = "Power failed on server " + $SystemName + " at " + $date + " on UPS2 " + $objItem.DeviceID
Send-MailMessage -From "PowerShell" -To "Admin " -Subject $subject -Body $body -priority High -smtpServer 91.0.0.35 -Encoding ([System.Text.Encoding]::UTF8)
$UPS[1,1] | Out-File c:\script\batterystatus2.log
Add-Content $file $body
}
If (($UPS[0,1] -eq 2) -and (Test-Path c:\script\batterystatus1.log))
{
$body=""
$subject = ""
$subject="Power restored on server " + $SystemName + " at " + $date + " on UPS1"
$body = "Power restored on server " + $SystemName + " at " + $date + " on UPS1 " + $objItem.DeviceID
Send-MailMessage -From "PowerShell" -To "Admin " -Subject $subject -Body $body -priority High -smtpServer 91.0.0.35 -Encoding ([System.Text.Encoding]::UTF8)
del c:\script\batterystatus1.log
Add-Content $file $body
}
If (($UPS[1,1] -eq 2) -and (Test-Path c:\script\batterystatus2.log))
{
$body=""
$subject = ""
$subject="Power restored on server " + $SystemName + " at " + $date + " on UPS2"
$body = "Power restored on server " + $SystemName + " at " + $date + " on UPS2 " + $objItem.DeviceID
Send-MailMessage -From "PowerShell" -To "Admin " -Subject $subject -Body $body -priority High -smtpServer 91.0.0.35 -Encoding ([System.Text.Encoding]::UTF8)
del c:\script\batterystatus2.log
Add-Content $file $body
}
#-------------------------------------------------------------------------------------------
#Stop-Computer -Credential $cred -ComputerName server7.bank.local -Force
$strComputer = "."
$colItems = get-wmiobject -class "Win32_Battery" -namespace "root\CIMV2" -computername $strComputer
$EstimatedChargeRemaining = new-object object[] 2
$UPS = New-Object "object[,]" 2,7
$i=0
$username = "bank\user"
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
#$serverNameOrIp = "192.168.1.1"
#Restart-Computer -ComputerName $serverNameOrIp `
# -Authentication default `
# -Credential $cred
foreach ($objItem in $colItems) {
$date = Get-Date
$file = 'c:\script\upslog'+$i+'.log'
if ($UPS[$i,2] -lt 100) {
Add-Content $file $date
$UPS[$i,0] = $objItem.DeviceID
$Temp = "Device ID: " + $UPS[$i,0]
Add-Content $file $Temp
$UPS[$i,1] = $objItem.BatteryStatus
$Temp = "Battery Status: " + $UPS[$i,1]
Add-Content $file $Temp
$UPS[$i,2] = $objItem.EstimatedChargeRemaining
$Temp = "Estimated Charge Remaining: " + $UPS[$i,2]
$Temp
$EstimatedChargeRemaining[$i] = $UPS[$i,2]
$EstimatedChargeRemaining[$i]
Add-Content $file $Temp
$UPS[$i,3] = $objItem.EstimatedRunTime
$Temp = "Estimated Run Time: " + $UPS[$i,3]
Add-Content $file $Temp
$UPS[$i,4] = $objItem.Status
$Temp = "Status: " + $UPS[$i,4]
Add-Content $file $Temp
$UPS[$i,5] = $objItem.SystemName
$Temp = "System Name: " + $UPS[$i,5]
$SystemName = $UPS[$i,5]
Add-Content $file $Temp
}
# write-host "Availability: " $objItem.Availability
# write-host "Battery Recharge Time: " $objItem.BatteryRechargeTime
# write-host "Battery Status: " $objItem.BatteryStatus
# write-host "Caption: " $objItem.Caption
# write-host "Chemistry: " $objItem.Chemistry
# write-host "Configuration Manager Error Code: " $objItem.ConfigManagerErrorCode
# write-host "Configuration Manager User Configuration: " $objItem.ConfigManagerUserConfig
# write-host "Creation Class Name: " $objItem.CreationClassName
# write-host "Description: " $objItem.Description
# write-host "Design Capacity: " $objItem.DesignCapacity
# Designed voltage of the battery in millivolts. If this attribute is not supported, enter 0.
# write-host "Design Voltage: " $objItem.DesignVoltage
# write-host "Device ID: " $objItem.DeviceID
# write-host "Error Cleared: " $objItem.ErrorCleared
# write-host "Error Description: " $objItem.ErrorDescription
# write-host "Estimated Charge Remaining: " $objItem.EstimatedChargeRemaining
# write-host "Estimated Run Time: " $objItem.EstimatedRunTime
# write-host "Expected Battery Life: " $objItem.ExpectedBatteryLife
# write-host "Expected Life: " $objItem.ExpectedLife
# write-host "Full Charge Capacity: " $objItem.FullChargeCapacity
# write-host "Installation Date: " $objItem.InstallDate
# write-host "Last Error Code: " $objItem.LastErrorCode
# write-host "Maximum Recharge Time: " $objItem.MaxRechargeTime
# write-host "Name: " $objItem.Name
# write-host "PNP Device ID: " $objItem.PNPDeviceID
# write-host "Power Management Capabilities: " $objItem.PowerManagementCapabilities
# write-host "Power Management Supported: " $objItem.PowerManagementSupported
# write-host "Smart Battery Version: " $objItem.SmartBatteryVersion
# write-host "Status: " $objItem.Status
# write-host "Status Information: " $objItem.StatusInfo
# write-host "System Creation Class Name: " $objItem.SystemCreationClassName
# write-host "System Name: " $objItem.SystemName
# write-host "Time On Battery: " $objItem.TimeOnBattery
# write-host "Time To Full Charge: " $objItem.TimeToFullCharge
$i=$i+1
}
#Общий лог
$file = "c:\script\upslog.log"
#Проверяем уровень разрядки и отправляем сообщения. Тушим сервера
if ($i=2){
#Если скрипт используется для контроля двух УПС
if (([int]$EstimatedChargeRemaining[0]+[int]$EstimatedChargeRemaining[1] -le 95) -and ($UPS[0,1] -eq 1) -and ($ups[1,1] -eq 1))
{
$sum = [int]$EstimatedChargeRemaining[0]+[int]$EstimatedChargeRemaining[1]
$date = Get-Date
Add-Content $file 'Sum Charege is'
Add-Content $file $sum
$subject=""
$subject = "Power failed on server " + $SystemName + " at " + $date
$body=""
$body = "Current charge on ups1 is " + $EstimatedChargeRemaining[0] + ". Current charge on ups2 is " + $EstimatedChargeRemaining[1]+ "."
$body = $body + " Estimate minutes of the time to battery charge depletion is " + $UPS[0,3] + " on ups1 and " + $UPS[1,3] + " on ups2."
$body = $body + " Shutdown Server7"
Send-MailMessage -From "PowerShell
Stop-Computer -Credential $cred -ComputerName server7.bank.local -Force
#Кол-во серверов для выключения не ограничено
}
}else
{
# Если скрипт используется для контроля одного УПС
if ([int]$EstimatedChargeRemaining[0] -le 95)
{
$date = Get-Date
Add-Content $file 'Sum Charege is'
Add-Content $file $EstimatedChargeRemaining[0]
$subject=""
$subject = "Power failed on server " + $SystemName + " at " + $date
$body=""
$body = "Current charge on ups is " + $EstimatedChargeRemaining[0]
$body = $body + " Estimate minutes of the time to battery charge depletion is " + $UPS[0,3]
$body = $body + " Shutdown Server7"
Send-MailMessage -From "PowerShell
Stop-Computer -Credential $cred -ComputerName server7.bank.local -Force
#Кол-во серверов для выключения не ограничено
}
}
#--------------------------------------------------------------------------------------------------------------------------------
#Фиксируем время віключения и включения єлектричества
If (($UPS[0,1] -eq 1) -and -not(Test-Path c:\script\batterystatus1.log))
{
$body=""
$subject = ""
$subject="Power failed on server " + $SystemName + " at " + $date + " on UPS1"
$body = "Power failed on server " + $SystemName + " at " + $date + " on UPS1 " + $objItem.DeviceID
Send-MailMessage -From "PowerShell
$UPS[0,1] | Out-File c:\script\batterystatus1.log
Add-Content $file $body
}
If (($UPS[1,1] -eq 1) -and -not(Test-Path c:\script\batterystatus2.log))
{
$body=""
$subject = ""
$subject="Power failed on server " + $SystemName + " at " + $date + " on UPS2"
$body = "Power failed on server " + $SystemName + " at " + $date + " on UPS2 " + $objItem.DeviceID
Send-MailMessage -From "PowerShell
$UPS[1,1] | Out-File c:\script\batterystatus2.log
Add-Content $file $body
}
If (($UPS[0,1] -eq 2) -and (Test-Path c:\script\batterystatus1.log))
{
$body=""
$subject = ""
$subject="Power restored on server " + $SystemName + " at " + $date + " on UPS1"
$body = "Power restored on server " + $SystemName + " at " + $date + " on UPS1 " + $objItem.DeviceID
Send-MailMessage -From "PowerShell
del c:\script\batterystatus1.log
Add-Content $file $body
}
If (($UPS[1,1] -eq 2) -and (Test-Path c:\script\batterystatus2.log))
{
$body=""
$subject = ""
$subject="Power restored on server " + $SystemName + " at " + $date + " on UPS2"
$body = "Power restored on server " + $SystemName + " at " + $date + " on UPS2 " + $objItem.DeviceID
Send-MailMessage -From "PowerShell
del c:\script\batterystatus2.log
Add-Content $file $body
}
#-------------------------------------------------------------------------------------------
#Stop-Computer -Credential $cred -ComputerName server7.bank.local -Force
cls
Add-PsSnapin Microsoft.SharePoint.PowerShell
Add-PSSnapin Quest.ActiveRoles.ADManagement
Start-SPAssignment -Global
$nl = [System.Environment]::NewLine
$spsite = New-Object Microsoft.SharePoint.SPSite("http://sharepoint")
$spweb = $spsite.OpenWeb()
$spList = $spWeb.GetList("/Lists/List5")
#Обновляем записи в домене
$spItems=$spList.Items
forEach($str in $spItems)
{
$LastName = $str["Фамилия"].trimend(' ')
$FirstName = $str["Имя"].trimend(' ')
$SecondName = $str["Отчество"].trimend(' ')
$Mobile = $str["Мобильный телефон"].trimend(' ')
[string]$id =$str['№']
$id = $id.Remove(0,$id.IndexOf('#')+1)
$id = $id.TrimEnd('0')
$id = $id.TrimEnd('.')
$dplname = $LastName+' '+$FirstName+' '+$SecondName
Get-QADUser -DisplayName $dplname | set-QADUser -MobilePhone $Mobile
$Mobile
Get-QADUser -DisplayName $dplname | Select-Object -Property MobilePhone
}
##Очищаем список от старых телефонов
$spItems = $spList.Items
$spitemscount = $spItems.count
For ($x=$spitemscount-1;$x -ge 0; $x--)
{
$spitems[$x].delete()
}
#Заносим данн. на сервер
[Array]$Users = Get-QADUSER -IncludeAllProperties
foreach ($item in $Users)
{
[string]$DP=$item.DisplayName
[array]$DP1 = $DP.Split(" ");
$Department=$item.Department
$PhoneNumber=$item.MobilePhone
$Title = $item.Title
$Last = $DP1[0]
$Name = $DP1[1]
$FName = $DP1[2]
if($PhoneNumber -ne $null){
$spitems = $spList.AddItem()
$spitems["Фамилия"] = $Last
$spitems["Имя"] = $Name
$spitems["Отчество"] = $FName
$spitems["Должность"] = $Title
$spitems["Отдел/Департамент/Отделение"] = $Department
$spitems["Мобильный телефон"] = $PhoneNumber
$spitems.update() }
}
$SPWeb.Dispose()
$spsite.Dispose()
STOP-SPAssignment -Global
cls
Add-PsSnapin Microsoft.SharePoint.PowerShell
Add-PSSnapin Quest.ActiveRoles.ADManagement
Start-SPAssignment -Global
$nl = [System.Environment]::NewLine
$spsite = New-Object Microsoft.SharePoint.SPSite("http://sharepoint")
$spweb = $spsite.OpenWeb()
$spList = $spWeb.GetList("/Lists/List5")
#Обновляем записи в домене
$spItems=$spList.Items
forEach($str in $spItems)
{
$LastName = $str["Фамилия"].trimend(' ')
$FirstName = $str["Имя"].trimend(' ')
$SecondName = $str["Отчество"].trimend(' ')
$Mobile = $str["Мобильный телефон"].trimend(' ')
[string]$id =$str['№']
$id = $id.Remove(0,$id.IndexOf('#')+1)
$id = $id.TrimEnd('0')
$id = $id.TrimEnd('.')
$dplname = $LastName+' '+$FirstName+' '+$SecondName
Get-QADUser -DisplayName $dplname | set-QADUser -MobilePhone $Mobile
$Mobile
Get-QADUser -DisplayName $dplname | Select-Object -Property MobilePhone
}
##Очищаем список от старх телефонов
$spItems = $spList.Items
$spitemscount = $spItems.count
For ($x=$spitemscount-1;$x -ge 0; $x--)
{
$spitems[$x].delete()
}
#Заносим данн. на сервер
[Array]$Users = Get-QADUSER
foreach ($item in $Users)
{
[string]$DP=$item.DisplayName
[array]$DP1 = $DP.Split(" ");
$Department=$item.Department
$PhoneNumber=$item.MobilePhone
$Title = $item.Title
$Last = $DP1[0]
$Name = $DP1[1]
$FName = $DP1[2]
if($PhoneNumber -ne $null){
$spitems = $spList.AddItem()
$spitems["Фамилия"] = $Last
$spitems["Имя"] = $Name
$spitems["Отчество"] = $FName
$spitems["Должность"] = $Title
$spitems["Отдел/Департамент/Отделение"] = $Department
$spitems["Мобильный телефон"] = $PhoneNumber
$spitems.update() }
}
$SPWeb.Dispose()
$spsite.Dispose()
STOP-SPAssignment -Global
Add-PsSnapin Microsoft.SharePoint.PowerShell
Add-PSSnapin Quest.ActiveRoles.ADManagement
Start-SPAssignment -Global
$nl = [System.Environment]::NewLine
$spsite = New-Object Microsoft.SharePoint.SPSite("http://sharepoint")
$spweb = $spsite.OpenWeb()
$spList = $spWeb.GetList("/Lists/List5")
#Обновляем записи в домене
$spItems=$spList.Items
forEach($str in $spItems)
{
$LastName = $str["Фамилия"].trimend(' ')
$FirstName = $str["Имя"].trimend(' ')
$SecondName = $str["Отчество"].trimend(' ')
$Mobile = $str["Мобильный телефон"].trimend(' ')
[string]$id =$str['№']
$id = $id.Remove(0,$id.IndexOf('#')+1)
$id = $id.TrimEnd('0')
$id = $id.TrimEnd('.')
$dplname = $LastName+' '+$FirstName+' '+$SecondName
Get-QADUser -DisplayName $dplname | set-QADUser -MobilePhone $Mobile
$Mobile
Get-QADUser -DisplayName $dplname | Select-Object -Property MobilePhone
}
##Очищаем список от старх телефонов
$spItems = $spList.Items
$spitemscount = $spItems.count
For ($x=$spitemscount-1;$x -ge 0; $x--)
{
$spitems[$x].delete()
}
#Заносим данн. на сервер
[Array]$Users = Get-QADUSER
foreach ($item in $Users)
{
[string]$DP=$item.DisplayName
[array]$DP1 = $DP.Split(" ");
$Department=$item.Department
$PhoneNumber=$item.MobilePhone
$Title = $item.Title
$Last = $DP1[0]
$Name = $DP1[1]
$FName = $DP1[2]
if($PhoneNumber -ne $null){
$spitems = $spList.AddItem()
$spitems["Фамилия"] = $Last
$spitems["Имя"] = $Name
$spitems["Отчество"] = $FName
$spitems["Должность"] = $Title
$spitems["Отдел/Департамент/Отделение"] = $Department
$spitems["Мобильный телефон"] = $PhoneNumber
$spitems.update() }
}
$SPWeb.Dispose()
$spsite.Dispose()
STOP-SPAssignment -Global
Рядом со скриптом обязательно должен лежать "dsacls.exe"
cls
Add-PSSnapin Quest.ActiveRoles.Admanagement
cls
[array]$q = Get-QADObject -Type 'Organizationalunit' -IncludeAllProperties
Foreach ($item in $q)
{
$item.DN
& dsacls $item.DN /S/T/resetDefaultDACL
#Get-QADPermission $item.DN -Inherited -SchemaDefault
}
[array]$q = Get-QADObject -Type 'User' -IncludeAllProperties
Foreach ($item in $q)
{
$item.DN
& dsacls $item.DN /S/T/resetDefaultDACL
#Get-QADPermission $item.DN -Inherited -SchemaDefault
}
[array]$q = Get-QADObject -Type 'Group' -IncludeAllProperties
Foreach ($item in $q)
{
$item.DN
& dsacls $item.DN /S/T/resetDefaultDACL
#Get-QADPermission $item.DN -Inherited -SchemaDefault
}
cls
[array]$q = Get-QADObject -Type 'Computer' -IncludeAllProperties
Foreach ($item in $q)
{
$item.DN
& dsacls $item.DN /S/T/resetDefaultDACL
#Get-QADPermission $item.DN -Inherited -SchemaDefault
}
cls
Add-PSSnapin Quest.ActiveRoles.Admanagement
cls
[array]$q = Get-QADObject -Type 'Organizationalunit' -IncludeAllProperties
Foreach ($item in $q)
{
$item.DN
& dsacls $item.DN /S/T/resetDefaultDACL
#Get-QADPermission $item.DN -Inherited -SchemaDefault
}
[array]$q = Get-QADObject -Type 'User' -IncludeAllProperties
Foreach ($item in $q)
{
$item.DN
& dsacls $item.DN /S/T/resetDefaultDACL
#Get-QADPermission $item.DN -Inherited -SchemaDefault
}
[array]$q = Get-QADObject -Type 'Group' -IncludeAllProperties
Foreach ($item in $q)
{
$item.DN
& dsacls $item.DN /S/T/resetDefaultDACL
#Get-QADPermission $item.DN -Inherited -SchemaDefault
}
cls
[array]$q = Get-QADObject -Type 'Computer' -IncludeAllProperties
Foreach ($item in $q)
{
$item.DN
& dsacls $item.DN /S/T/resetDefaultDACL
#Get-QADPermission $item.DN -Inherited -SchemaDefault
}
import-module ActiveDirectory
Function Get-UserMembership
{
Param($UserAccount)
Process
{
Try {
$Groups = (Get-ADUser -Identity $UserAccount -Properties MemberOf | `
Select-Object MemberOf).MemberOf
}
Catch {
Return $Nothing
}
$GroupItems = @()
ForEach ($Group in $Groups)
{
$var = $group.split(",")
$var1 = $var[0]
$ADGroup = $var1.Substring(3)
$GrpItems = New-Object -TypeName PSObject -Property @{
Memberof = $ADGroup}
$GroupItems += $GrpItems
}
Return $GroupItems | Sort memberOf
}
}
Function Get-UserMembership_ByName {
Param($UserName)
Process
{
Try {
$ResultNumber = (Get-ADUser -Filter {Name -eq $UserName} | Measure-Object).Count
}
Catch {
Return $Nothing
}
If ($ResultNumber -eq 0) {
Write-Host "There is no such user in the system."
Return $Nothing
}
ElseIf ($ResultNumber -ge 2) {
Write-Host "There are several users in the system with the provided name." `
"Please use the user account way."
Return $Nothing
}
Else {
$Groups = (Get-ADUser -Filter {Name -eq $UserName} -Properties memberof | `
Select-Object MemberOf).memberof
$GroupItems = @()
ForEach ($Group in $Groups) {
$var = $group.split(",")
$var1 = $var[0]
$ADGroup = $var1.Substring(3)
$GrpItems = New-Object -TypeName PSObject -Property @{
Memberof = $ADGroup}
$GroupItems += $GrpItems
}
Return $GroupItems | Sort memberOf
}
}
}
$UserAccount = $Nothing
$UserAccount = Read-Host 'What is the user account? (Type nothing to search by a user name)'
If ($UserAccount -eq '') {
$UserAccount = Read-Host 'What is the user name? (Last name and first name)'
$Result = UserMembership_ByName $UserAccount | Sort Memberof
}
Else {
$Result = Get-UserMembership $UserAccount | Sort Memberof
}
If ($Result -eq $Nothing) {
Write-Host "Nothing is found. The result file is not created."
}
Else {
$OutFile = (Get-Childitem env:USERPROFILE).Value + "\Desktop\$UserAccount.csv"
$Result | Export-Csv $OutFile -Delimiter "`t" -Encoding UTF8
Write-Host "The result is in $OutFile file."
}
Get-UserMembership GroupName
Function Get-UserMembership
{
Param($UserAccount)
Process
{
Try {
$Groups = (Get-ADUser -Identity $UserAccount -Properties MemberOf | `
Select-Object MemberOf).MemberOf
}
Catch {
Return $Nothing
}
$GroupItems = @()
ForEach ($Group in $Groups)
{
$var = $group.split(",")
$var1 = $var[0]
$ADGroup = $var1.Substring(3)
$GrpItems = New-Object -TypeName PSObject -Property @{
Memberof = $ADGroup}
$GroupItems += $GrpItems
}
Return $GroupItems | Sort memberOf
}
}
Function Get-UserMembership_ByName {
Param($UserName)
Process
{
Try {
$ResultNumber = (Get-ADUser -Filter {Name -eq $UserName} | Measure-Object).Count
}
Catch {
Return $Nothing
}
If ($ResultNumber -eq 0) {
Write-Host "There is no such user in the system."
Return $Nothing
}
ElseIf ($ResultNumber -ge 2) {
Write-Host "There are several users in the system with the provided name." `
"Please use the user account way."
Return $Nothing
}
Else {
$Groups = (Get-ADUser -Filter {Name -eq $UserName} -Properties memberof | `
Select-Object MemberOf).memberof
$GroupItems = @()
ForEach ($Group in $Groups) {
$var = $group.split(",")
$var1 = $var[0]
$ADGroup = $var1.Substring(3)
$GrpItems = New-Object -TypeName PSObject -Property @{
Memberof = $ADGroup}
$GroupItems += $GrpItems
}
Return $GroupItems | Sort memberOf
}
}
}
$UserAccount = $Nothing
$UserAccount = Read-Host 'What is the user account? (Type nothing to search by a user name)'
If ($UserAccount -eq '') {
$UserAccount = Read-Host 'What is the user name? (Last name and first name)'
$Result = UserMembership_ByName $UserAccount | Sort Memberof
}
Else {
$Result = Get-UserMembership $UserAccount | Sort Memberof
}
If ($Result -eq $Nothing) {
Write-Host "Nothing is found. The result file is not created."
}
Else {
$OutFile = (Get-Childitem env:USERPROFILE).Value + "\Desktop\$UserAccount.csv"
$Result | Export-Csv $OutFile -Delimiter "`t" -Encoding UTF8
Write-Host "The result is in $OutFile file."
}
Get-UserMembership GroupName
Комментарии