Разные cкрипты для Powershell

Main

Оценка: 86.21% - 14 Голосов

Общая

Буду хранить здесь разные говноскриптики для управления и получения информации из AD и прочих продуктов Microsoft.

Скрипты для Exchange

Выполнение данных скриптов происходит в Exchange Management Shell

 

Скрипт загрузки фотографий в учетные записи.

Фотографии должны быт 640х640 пикселей.

Скрипт берет файлы из папки с обработанными фотографиями.


param([Switch]$all,[Switch]$Hide,[Switch]$CheckOnly, [String]$UserNameSam)
$PhotoPath = "C:\UserPhotos\"
$ProceedPhotoPath = "C:\UserPhotos\Done\"
$OU = 'Группа с пользователями в AD'
$UserPhotoCount = 0
$UserCount = 0
Function CheckPhoto($UserSamName_in, $UserPhotoFile_in)
{
    $result  = $false;
    if (Test-Path $UserPhotoFile_in)
    {
        if( $Hide -eq $false) {
            Write-Host "Найден:'$UserPhotoFile' для $UserName($UserSam_in)... " -ForegroundColor Green -NoNewline }
        $result = $true
    }
    else
    {
        $result = $false
        Write-Host "Не найден:$UserPhotoFile" -ForegroundColor Gray
    }
    return $result
}
Function SetPhoto($UserSamName_in, $UserPhotoFile_in)
{
    $check_result = CheckPhoto $UserSamName_in $UserPhotoFile_in;
    $result = $false
    if($check_result -eq $true)
    {
        if($CheckOnly -eq $false)
        {
            $UserPhoto =  ([Byte[]] $(Get-Content  -Path $UserPhotoFile_in -Encoding Byte -ReadCount 0))
            Set-UserPhoto -Identity $UserSamName_in -PictureData $UserPhoto -Confirm:$False
            $result=$true    
            if( $Hide -eq $false) {
                Write-Host "Загружен" -ForegroundColor Green }
        }
        else
        {
            if( $Hide -eq $false) {
                Write-Host "Посчитан" -ForegroundColor Green }
        }
    }
    return $result
}
Write-Host "ExchangePhotoUpload.ps1 [-all] [-check] [UserNameSam] [PhotoFile]"
$users = Get-User -OrganizationalUnit $OU
if ( $all -eq $true)
{
    Write-Warning "## Загрузка фотографий для всех пользователей в OU=$OU из $PhotoPath"
    foreach ($user in $users)
    {
        $UserName = $user.Name
        $UserPhotoFile = $($PhotoPath+$UserName+".jpg")
        $UserCount++
        if(SetPhoto $user.SamAccountName $UserPhotoFile)
        {
            $UserPhotoCount++
        }
    }
}
else
{
    foreach ($user in $users)
    {
        if($UserNameSam -eq $user.SamAccountName)
        {
            $UserCount++
            $UserName = $user.Name
            Write-Warning "## Загрузка фотографии для $UserName в OU=$OU из $PhotoPath"
            $UserPhotoFile = $($PhotoPath+$UserName+".jpg")
            #Write-Error "($UserPhotoFile)"
            if(SetPhoto $user.SamAccountName $UserPhotoFile)
            {
                $UserPhotoCount++
            }
        }
    }
    if($CheckOnly -eq $true) {
        Write-Host "Найдено:" -NoNewline }
    else {
        Write-Host "Загружено:" -NoNewline }
    Write-Host " $UserPhotoCount фотографий для $UserCount пользователей"
 }

 

 

 

Очистка логов Exchange

Что бы Exchange не толстел своими всевозможными логами.

Пути установки могут отличаться - проверь пути.

 


Set-Executionpolicy RemoteSigned
$days=0
$IISLogPath="C:\inetpub\logs\LogFiles\"
$ExchangeLoggingPath="C:\Program Files\Microsoft\Exchange Server\V15\Logging\"
$ETLLoggingPath="C:\Program Files\Microsoft\Exchange Server\V15\Bin\Search\Ceres\Diagnostics\ETLTraces\"
$ETLLoggingPath2="C:\Program Files\Microsoft\Exchange Server\V15\Bin\Search\Ceres\Diagnostics\Logs"
Function CleanLogfiles($TargetFolder)
{
    if (Test-Path $TargetFolder) {
        $Now = Get-Date
        $LastWrite = $Now.AddDays(-$days)
        $Files = Get-ChildItem $TargetFolder -Include *.log,*.blg, *.etl, *.txt -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}
        foreach ($File in $Files)
            {Write-Host "Deleting file $File" -ForegroundColor "white"; Remove-Item $File -ErrorAction SilentlyContinue | out-null}
       }
Else {
    Write-Host "The folder $TargetFolder doesn't exist! Check the folder path!" -ForegroundColor "white"
    }
}
CleanLogfiles($IISLogPath)
CleanLogfiles($ExchangeLoggingPath)
CleanLogfiles($ETLLoggingPath)
CleanLogfiles($ETLLoggingPath2)
gci -Path ‘C:\Program Files\Microsoft\Exchange Server\V15\Logging’,’C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs’,’D:\iislog\’ -Include ‘*.log’,’*.blg’,’*.bak’ -Recurse -Force | ? LastWriteTime -lt (Get-Date).AddDays(-14) | Remove-Item -Recurse -Force

 

Для работы с Active Directory
Выгрузить список Пользователей с ПК

У каждого ПК в AD указан пользователь управляющий им. ПК пользователей выбираются по маске с определённой группы в 75 строке скрипта.

Данный скрип позволяет создать список пользователей с выгрузкой ФИО, должности, отдела, телефона, привязанных к ним ПК и прочего в CSV. И используется для автоматической постановки пользовательских ПК в систему мониторинга Icinga2.


function Write-Log
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true)]
        [ValidateNotNullOrEmpty()]
        [Alias("LogContent")]
        [string]$Message,
 
        [Parameter(Mandatory=$false)]
        [Alias('LogPath')]
        [string]$Path='C:\Temp\PowerShellLog.log',
         
        [Parameter(Mandatory=$false)]
        [ValidateSet("Error","Warn","Info")]
        [string]$Level="Info",
         
        [Parameter(Mandatory=$false)]
        [switch]$NoClobber
    )
    Begin
    {
        # Set VerbosePreference to Continue so that verbose messages are displayed.
        $VerbosePreference = 'Continue'
    }
    Process
    {
        # If the file already exists and NoClobber was specified, do not write to the log.
        if ((Test-Path $Path) -AND $NoClobber) {
            Write-Error "Log file $Path already exists, and you specified NoClobber. Either delete the file or specify a different name."
            Return
            }
        # If attempting to write to a log file in a folder/path that doesn't exist create the file including the path.
        elseif (!(Test-Path $Path)) {
            Write-Verbose "Creating $Path."
            $NewLogFile = New-Item $Path -Force -ItemType File
            }
        else {
            # Nothing to see here yet.
            }
        # Format Date for our Log File
        $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        # Write message to error, warning, or verbose pipeline and specify $LevelText
        switch ($Level) {
            'Error' {
                Write-Error $Message
                $LevelText = 'ERROR:'
                }
            'Warn' {
                Write-Warning $Message
                $LevelText = 'WARNING:'
                }
            'Info' {
                Write-Verbose $Message
                $LevelText = 'INFO:'
                }
            }
        # Write log entry to $Path
        "$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append
    }
    End
    {
    }
}
$global:Path  = 'C:\Temp\MyLogFile.log'
$ComputerList = get-adcomputer -Filter {(Name -like "WS-*")} -SearchBase "OU=Рабочие станции,OU=Персональные компьютеры,DC=123,DC=ru" -properties Name,DNSHostName,Managedby | select Name,DNSHostName,@{n="Managedby";e={($_.Managedby)}},@{n="Username";e={($_.Managedby -split ",*..=")[1]}}
$Output = @()
foreach ($PC in $ComputerList) {
   $PcName = $PC.Name
   Write-Log -Message "Get computer name in AD [$($PcName)]"
   $DNSHostName = $PC.DNSHostName
   Write-Log -Message "Get computer DNS name [$($DNSHostName)]"
   $Username = $PC.Username
   Write-Log -Message "Get computer controller username [$($PC.Username)]"
   $ManagedBy = $PC.Managedby
   Write-Log -Message "Get AD user distinguished name  [$($PC.Managedby)]"
   if ($ManagedBy) {
    $user = get-aduser -identity "$ManagedBy" -Properties Mail,telephoneNumber,physicalDeliveryOfficeName,department,title
    $PrimarySMTP = $user.Mail
    $Phone = $user.telephoneNumber
    $Room = $user.physicalDeliveryOfficeName
    $Department = $user.department
    $Position = $user.title
    $Description = $PcName + ", " + $Position + " " + $Username + ", " + $Department + ", Каб: " + $Room + ", Тел: " + $Phone
    Write-Log -Message "Get user info [$($PrimarySMTP)($Phone)($Room)($Department)($Position)]"
    $MyObject = New-Object PSObject -Property @{
        PcName = $PC.Name -replace "-", ""
        ManagedBy = $Username
        PrimarySMTP = $PrimarySMTP
        Phone = $Phone
        Room = $Room
        Department = $Department
        Position = $Position
        DNSHostName = $PC.DNSHostName
        Description =  $Description
    }
   }else
  {
    $MyObject =  New-Object PSObject -Property @{
        PcName = $PC.Name -replace "-", ""
        ManagedBy = ""
        PrimarySMTP = ""
        Phone = ""
        Room = ""
        Department = ""
        Position = ""
        DNSHostName = ""
        Description = ""
    }
   }
$Output += $MyObject
Write-Log -Message "Create File [$($MyObject)]"
}
$Output | select PcName, ManagedBy, PrimarySMTP, Phone, Room, Department, Position, DNSHostName, Description  | Export-CSV -delimiter ";" C:\Temp\userpc1.csv -force -NoTypeInformation -Encoding UTF8

 

Создание пользователей в AD из CSV.

Пример файла CSV тут


$Users = Import-Csv -Delimiter ";" -Path "C:\Temp\newuser.csv"            
foreach ($User in $Users)            
{   
    $sn = $User.sn
    $givenName = $User.givenName
    $middleName = $User.middleName
    $name = $User.name
    $displayName = $User.displayName
    $title = $User.title
    $l = $User.l
    $company = $User.company
    $department = $User.department
    $SamAccountName = $User.SamAccountName
    $AccountPassword = ConvertTo-SecureString -AsPlainText $User.AccountPassword -force
    $UserPrincipalName = $User.UserPrincipalName
    $mail = $User.mail
    $manager = $User.manager
    $physicalDeliveryOfficeName = $User.physicalDeliveryOfficeName
    $telephoneNumber = $User.telephoneNumber
    $streetAddress = $User.streetAddress
    $profilePath = $User.profilePath
    
    New-ADUser -Manager "$manager" -Name "$name" -Surname "$sn" -GivenName "$givenName" -OtherName "$middleName" -DisplayName "$displayName" -title "$title" -l "$l" -Company "$company" -Department "$department" -SamAccountName "$SamAccountName" -AccountPassword $AccountPassword -UserPrincipalName "$UserPrincipalName" -EmailAddress "$mail" -Office "$physicalDeliveryOfficeName" -OfficePhone "$telephoneNumber" -streetAddress "$streetAddress" -profilePath "$profilePath" -ChangePasswordAtLogon $true
}

 

Комментарии   
0 #1 Earnestine 28.03.2017 05:24
Great post. I was checking continuously this blog and I'm impressed!
Extremely useful information particularly the last part :
) I care for such info a lot. I was seeking this particular information for a very long time.
Thank you and good luck.
Цитировать
Добавить комментарий


Logo