Перейти к содержимому

powershell

Как удалить site и pools из windows iis с помощью powershell.Deleting sites and application pools from Microsoft IIS using PowerShell

Удалить po0ls

#Deleting Sites and app pools in IIS 7 with PowerShell
$appCmd = "C:\windows\system32\inetsrv\appcmd.exe"

#lists all the sites
#& $appcmd list site 
#deletes a specific site
#& $appcmd delete site "Name of site"
#lists all the sites
#& $appcmd list apppool 
#deletes a specific application pool
#& $appcmd delete apppool "Name of app pool"
#delete any app pools that use a certain username (in the identity column of the GUI)
#$account = "TheDomain\TheAccount"
$AppPools = & $appcmd list apppool 
foreach ($pool in $AppPools){
    $pool = $pool.split(" ")[1] #get the name only
    & $appcmd delete apppool $pool
}
#delete all 
Читать далее

Как искать внутри GPO групповых политик.

Задача была найти политику где изменяется host на пк. Нашёл с помощью скрипта на powershell.

# Get the string we want to search for 
$string = Read-Host -Prompt "What string do you want to search for?" 
 
# Set the domain to search for GPOs 
$DomainName = $env:USERDNSDOMAIN 
 
# Find all GPOs in the current domain 
write-host "Finding all the GPOs in $DomainName" 
Import-Module grouppolicy 
$allGposInDomain = Get-GPO -All -Domain $DomainName 
[string[]] $MatchedGPOList = @()

# Look through each GPO's XML for the string 
Write-Host "Starting search...." 
foreach ($gpo in $allGposInDomain) { 
    $report = Get-GPOReport -Guid $gpo.Id -ReportType Xml 
    if ($report 
Читать далее

Как остановить и запустить все пулы iis через Powershell

Остановить pools iis через Powershell

Import-Module WebAdministration

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }

$AppPools=Get-ChildItem IIS:\AppPools | Where {$_.State -eq "Started"}

ForEach($AppPool in $AppPools)
{
 Stop-WebAppPool -name $AppPool.name
# Write-Output ('Stopping Application Pool: {0}' -f $AppPool.name)
}

Запустить pools iis через Powershell

Import-Module WebAdministration

   if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }

   $AppPools=Get-ChildItem IIS:\AppPools | Where {$_.State -eq "Stopped"}
   ForEach($AppPool in $AppPools)
   {
    Start-WebAppPool -name $AppPool.name
   # Write-Output ('Starting Application Pool: {0}' -f $AppPool.name)
   }

 

Как с клонировать или распространить роли (Roles and features ) на множество серверов с источника.

Скопировать роли (Roles and features ) с одного сервера на другой

Get-WindowsFeature | where{$_.Installed -eq $True} | select name | foreach{Install-WindowsFeature -ComputerName servername $_.name}

Экспортировать в csv потом импортировать.

Get-WindowsFeature | where{$_.Installed -eq $True} | select name | Export-Csv C:\ps\Roles.csv -NoTypeInformation –Verbose

Import-Csv C:\PS\Roles.csv | foreach{ Install-WindowsFeature $_.name }

 

Как выгрузить в csv список отправленных писем. Кто отправил и кому за 7 дней. Exchange

Get-TransportServer | get-messagetrackinglog -EventID “send” -Start (Get-Date).AddDays(-7) -ResultSize Unlimited | Select timestamp, eventid, Source,Messageid, MessageSubject, sender,@{Name=’recipients‘;Expression={[string]::join(“;”, ($_.recipients))}}, clientip, clienthostname, serverip, serverhostname, messageinfo | export-csv C:\message_log.csv

С заменой system.string

Хорошая ссылка https://www.millersystems.com/powershell-exporting-multi-valued-attributes-via-export-csv-cmdlet/

Как массово создать учётные записи в АД из csv файла

Import-Module ActiveDirectory
Import-Csv -Path C:\user\1.csv -Encoding Default -Delimiter ";" |
foreach-object{
  Write-Host "Username" $_.CN "not exists " $_.SamAccountName.Length
   if ($_.SamAccountName.Length  -gt 20 ) {  $_.SamAccountName=$_.SamAccountName.Substring(0,20)
 Write-Host $_.SamAccountName}
 $Firstname=''
 $FirstName=$_.FirstName
 $filter="SamAccountName -eq '"+$_.SamAccountName+"'"
 $usrexist=get-aduser -filter $filter


  if ($usrexist -eq $null)
  {

  new-aduser -Name $_.CN.trim() -DisplayName $_.DisplayName.trim() -City $_.City -Department $_.Department -Surname $_.Surname -GivenName $_.Givename  -SamAccountName $_.SamAccountName   -Title $_.title -POBox $_.postOfficeBox -AccountPassword (ConvertTo-SecureString '123456Q!' -AsPlainText -force) -Path "OU=Temp,DC=adminbd,DC=ru" -UserPrincipalName $_.emailaddress -Enabled $true -ChangePasswordAtLogon $true
  }
  else
  {
  
  Write-Host "Username" $_.CN "exists" -ForegroundColor Red
  
  }}

Формат csv

Как массово создать учётные записи в АД из csv файла

Как создать контакты exchange почты из домена организации с помощью powershell.

add-pssnapin quest.activeroles.admanagement
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn
#Адрес контроллера домена, к которому подключаемся";
$Domain = 'namedomen.ru'
Connect-QADService -Service $Domain
#Получаем список пользователей удаленного домена   
$userlist = (Get-QADUser -name [А-Я]* -IncludedProperties DisplayName, title, company, department, mailNickname, Office, l, firstname, sn, PhoneNumber, Mobile, Email, physicalDeliveryOfficeName, AccountIsDisabled, msExchMailboxGuid -SizeLimit 0)
ForEach ($user in $userlist)
 {
 #Пользователь заблокирован?
 if ($user.AccountIsDisabled -eq $true) 
   {
  #У пользователя есть почта?
  if ($user.msExchMailboxGuid -notlike $NULL)   {
   #Пользователь заблокирован, удаляем существующий контакт
   Remove-MailContact $user.mail –Confirm:$false
   }
  }
 elseif ($(Get-contact $user.displayname))
  {
  if ($user.mail -notlike $NULL)
   {
   #Пользователь не заблокирован, контакт существует, надо обновить
   Set-Contact $user.email -Company "Имя компании" -Title $user.Title -Department $user.Department 
Читать далее

Как создать учётные записи с помощью powershell в AD из csv

Import-Csv -Path C:\1.csv -Encoding Default -Delimiter ";" | sort CN |
foreach-object{
#New-ADUser -Name $_.Full_Name -AccountPassword (ConvertTo-SecureString 'password!' -AsPlainText -force) -CannotChangePassword $True -Description $_.Desc -DisplayName $_.Full_Name -EmailAddress $_.Email -Enabled $False -GivenName $_.First_Name -HomeDirectory $_.Homedir -HomeDrive $Homedri -PasswordNeverExpires $True -Path $_.Path -SamAccountName $_.Email -ScriptPath LogonS.cmd -Surname $_.Last_Name -UserPrincipalName $_.Email -passthru
#Write-Host $_.SamAccountName
$filter="SamAccountName -eq '"+$_.SamAccountName+"'"
$usrexist=get-aduser -filter $filter
#Write-Host $_.SamAccountName
#Write-Host $_.SamAccountName
if ($usrexist -eq $null)
{
Write-Host "Username" $_.CN "not exists " $_.SamAccountName.Length
if ($_.SamAccountName.Length -gt 20 ) { $_.SamAccountName=$_.SamAccountName.Substring(0,20)
Write-Host $_.SamAccountName}
if (!$_.emailaddress){ $_.emailaddress=$_.SamAccountName+'@domen.ru'}
# write-host -Name $_.CN -DisplayName $_.DisplayName -City $_.City -Department $_.Department -Surname $_.Surname -GivenName $_.Givenname -SamAccountName 
Читать далее

Как завершить сессию на всех серверах в локальной сети.

Проблема при смене пароля на серверах остались отключенные сессии . Из-за этого блокируется учётная запись. Надо сессию завершить на всех серверах . но так как серверов больше 500 в ручную делать это негуманно к себе.

вот скрипт . Запускается от пользователя которого надо завершить

param (
        #get current logged on username
        [string]$UserName = $env:USERNAME
    )

    # Импортировать модуль Active Directory для Get-ADComputer CmdLet
    Import-Module ActiveDirectory


    # Запрос Active Directory для включенных учетных записей компьютеров серверов Windows и сортировка по имени
    $Servers = Get-ADComputer -Filter {(OperatingSystem -like "*windows*server*") -and (Enabled -eq "True")} | Sort Name

    
# Инициирующие переменные
    $SessionList = $NULL
    
Читать далее