📜 ⬆️ ⬇️

Upload a user's photo in Active Directory using PowerShell

If you use Active Directory you use Exchange, OwnCloud, SharePoint or another system with the ability to display an avatar or a photo, then after reading this article you will have the opportunity to upload a user's photo in AD for display in Outlook, Lync, on SharePoint portals and other systems .

I found a similar article ( “Adding photos to Active Directory” ), but it took a long time, I decided to revive the topic.

Requirements:


Minuses:

')
For reference:
Active Directory restriction on the size of the thumbnailPhoto attribute and jpegPhoto 100 kb. The user's photo in Outlook 2010 will be displayed even if Exchange is not installed, it is enough to have an Active Directory Win 2008 scheme or newer (This does not mean the presence of controllers under Window 2008, just run adprep from a Windows 2008 disk to extend the scheme). To display user photos, in different systems, different attributes are used in Active Directory. For example, for display in Outlook thumbnailPhoto, and for display in SharePoint jpegPhoto.


The author is not responsible for any possible harm caused by the materials of this article.

The article does not provide the entire script. The taste and color markers are different.
In fact, with my ready-made script, if it is thoughtlessly used, it is easier to break the Active Directory.



Or finish equipment Active Directory User & computers


There are several options for uploading photos to AD using PowerShell:

Using the Microsoft PowerShell for Active Directory module:

Import-Module ActiveDirectory $photo = [byte[]](Get-Content C:\Photo\MyPhoto.jpg -Encoding byte) Set-ADUser <sAMAaccountName> -Replace @{thumbnailPhoto=$photo} Set-ADUser <sAMAaccountName> -Replace @{jpegPhoto;=$photo} 

Using the Quest PowerShell for Active Directory snap-in:

 Add-PSSnapin Quest.ActiveRoles.ADManagement $photo = [byte[]](Get-Content C:\Photo\MyPhoto.jpg -Encoding byte) Set-QADUser <sAMAaccountName> -ObjectAttributes @{thumbnailPhoto=$photo} Set-QADUser <sAMAaccountName> -ObjectAttributes @{jpegPhoto=$photo} 

Using the PowerShell for Exchange snap-in:

 Add-PSSnapin Microsoft.Exchange.Management.Powershell.E2010 Import-RecipientDataProperty -Identity <sAMAaccountName> -Picture -FileData ([Byte[]]$(Get-Content -Path "C:\Photo\MyPhoto.jpg" -Encoding Byte -ReadCount 0)) 

Limit snap on file size 10 KB. Replaces only thumbnailphoto.

Using PowerShell for Exchange 2013:

 Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn $photo = ([Byte[]] $(Get-Content -Path "C:\Photo\MyPhoto.jpg" -Encoding Byte -ReadCount 0)) Set-UserPhoto -Identity <sAMAaccountName> -PictureData $photo -Confirm:$False Set-UserPhoto -Identity <sAMAaccountName> -Save -Confirm:$False 

Check the photo through the browser (if you have Exchange 2013)
https: //mail.domain.local/ews/Exchange.asmx/s/GetUserPhoto? email=user@domain.com&size=HR648x648


Using PowerShell and ADSI:

 [byte[]]$jpg = Get-Content "C:\Photo\MyPhoto.jpg" -encoding byte $user = [adsi]"LDAP://cn=user1,cn=users,dc=domain,dc=loc" $user.Properties["jpegPhoto"].Clear() $null = $user.Properties["jpegPhoto"].Add($jpg) $user.Properties["thumbnailPhoto"].Clear() $null = $user.Properties["thumbnailPhoto"].Add($jpg) $user.CommitChanges() 

All these examples load the user's photo without changing the size and quality of the picture.

For myself, I stopped to use with the module Microsoft PowerShell for Active Directory. But at the first attempt to upload a photo I received an error about the impossibility of loading a photo from a file of 5 megabytes in size. The first idea was to convert the photos, squeezing them to an acceptable size. But the desire to learn PowerShell won.

So complicate the task of uploading photos. Add a function to change the photo resolution.

The function takes as input the full path to the file, the maximum resolution, the quality of compression.

Almost finished function was found on the Internet and dopilena for specific tasks.
 Function resizephoto(){ Param ( [Parameter(Mandatory=$True)] [ValidateNotNull()] $imageSource, [Parameter(Mandatory=$true)][ValidateNotNull()] $canvasSize, [Parameter(Mandatory=$true)][ValidateNotNull()] $quality ) #       #  if (!(Test-Path $imageSource)){throw( "  ")} if ($canvasSize -lt 10 -or $canvasSize -gt 1000){throw( "      10  1000")} if ($quality -lt 0 -or $quality -gt 100){throw( "      0  100")} [void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") $imageBytes = [byte[]](Get-Content $imageSource -Encoding byte) $ms = New-Object IO.MemoryStream($imageBytes, 0, $imageBytes.Length) $ms.Write($imageBytes, 0, $imageBytes.Length); $bmp = [System.Drawing.Image]::FromStream($ms, $true) #     $canvasWidth = $canvasSize $canvasHeight = $canvasSize #    $myEncoder = [System.Drawing.Imaging.Encoder]::Quality $encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1) $encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter($myEncoder, $quality) #   $myImageCodecInfo = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders()|where {$_.MimeType -eq 'image/jpeg'} #   $ratioX = $canvasWidth / $bmp.Width; $ratioY = $canvasHeight / $bmp.Height; $ratio = $ratioY if($ratioX -le $ratioY){ $ratio = $ratioX } #    $newWidth = [int] ($bmp.Width*$ratio) $newHeight = [int] ($bmp.Height*$ratio) $bmpResized = New-Object System.Drawing.Bitmap($newWidth, $newHeight) $graph = [System.Drawing.Graphics]::FromImage($bmpResized) $graph.Clear([System.Drawing.Color]::White) $graph.DrawImage($bmp,0,0 , $newWidth, $newHeight) #    $ms = New-Object IO.MemoryStream $bmpResized.Save($ms,$myImageCodecInfo, $($encoderParams)) #  $bmpResized.Dispose() $bmp.Dispose() return $ms.ToArray() } 


Paste this function into the script.

Fragment of the main part of the script, register the path to the photo, login, personnel number, full name
  $PhotoPath = '\\server\FOTO\' # PSDrive            PSSQL New-PSDrive -Name Photo -PSProvider FileSystem -Root $PhotoPath $UserLogin = 'login' $EmployeeID = '503' $FullName = 'Full User Name' #     write-host ": `n : " $UserLogin "`n :" $EmployeeID "`n : " $FullName #     AD    $aduser = get-aduser $UserLogin -ErrorAction SilentlyContinue if ($aduser.name -ne $FullName) { #           write-host "in Office " $FullName "`n in ad " $aduser.name "`nLogin " $UserLogin " `n`n" -ForegroundColor Red } else { #  EmployeeID  AD    Set-ADUser $UserLogin -EmployeeID $EmployeeID $PhotoFile = 'Photo:\'+$EmployeeID+'.jpg' #     If (Test-Path $PhotoFile ) { #     #       $thumbnailPhoto = [byte[]]( $(resizephoto $PhotoFile 64 80)) $jpegPhoto = [byte[]]( $(resizephoto $PhotoFile 648 80)) #    thumbnailPhoto Set-ADUser $UserLogin -Replace @{thumbnailPhoto=$thumbnailPhoto} -ErrorVariable ErrorthumbnailPhoto #-WhatIf if ($ErrorthumbnailPhoto -ne $null) { #    write-host "  thumbnailPhoto   "$UserLogin " ID " $_.autokey exit } #    jpegPhoto Set-ADUser $UserLogin -Replace @{jpegPhoto=($jpegPhoto)} -ErrorVariable ErrorjpegPhoto #-WhatIf if ($ErrorjpegPhoto -ne $null) { #    write-host "  jpegPhoto   "$UserLogin " ID " $_.autokey exit } if (!$ErrorthumbnailPhoto -and !$ErrorjpegPhoto) { #    #     write-host '...' -ForegroundColor Green } } else { #    Write-Host "  " $PhotoFile "  " $UserLogin "  " -foregroundcolor red } } 


The path to the photo is set via PSDrive, because after connecting the PowerShell PSSQL module for working with MS SQL, the current path changes to PS SQLSERVER: \> and accessing network resources without changing the folder becomes impossible. The photo is stored on a network resource, where the name of the file is the personnel number. In the example, logging and error handling is removed.


Uploading photos from Active Directory:
A few examples to verify the correctness of downloading photos in Active Directory.

Using the Microsoft PowerShell for Active Directory module:

 Import-Module ActiveDirectory $user = Get-ADUser <sAMAaccountName> -Properties thumbnailphoto , jpegPhoto $user.thumbnailphoto | Set-Content $env:temp\thumbnailphoto.jpg -Encoding byte $user.jpegPhoto | Set-Content $env:temp\jpegPhoto.jpg -Encoding byte 

Using PowerShell and ADSI:

 $username=$env:username $domain=$env:userdomain $temp=$env:temp $thumbnailphoto = ([ADSISEARCHER]"samaccountname=$($username)").findone().properties.thumbnailphoto if(!($thumbnailphoto -eq $null)) {$thumbnailphoto | set-content $temp\$domain+$username.thumbnailphoto.jpg -Encoding byte} $jpegphoto = ([ADSISEARCHER]"samaccountname=$($username)").findone().Properties.jpegphoto if(!($jpegphoto -eq $null)) {$jpegphoto | set-content $temp\$domain+$username.jpegPhoto.jpg -Encoding byte} 

Search users with / without photos:

 Import-Module ActiveDirectory Get-ADUser -Filter * -properties thumbnailPhoto | ? {$_.thumbnailPhoto} | select Name Get-ADUser -Filter * -properties thumbnailPhoto | ? {(-not($_.thumbnailPhoto))} | select Name Get-ADUser -Filter * -properties jpegPhoto | ? {$_.jpegPhoto} | select Name Get-ADUser -Filter * -properties jpegPhoto | ? {(-not($_.jpegPhoto))} | select Name 

What else can I do with photos uploaded to Active Directory?

Using photos from AD in the Windows menu
"Use AD Photos as Windows 7 User Tiles" ;
"Set Windows 7 User Tile to AD Thumbnail pic" .

Or write your telephone directory as titulusdesiderio " Telephone Directory" with blackjack and photo.

Source: https://habr.com/ru/post/252119/


All Articles