Download photos of the user in Active Directory using PowerShell
If you are using Active Directory you use Exchange, OwnCloud, SharePoint or another system with the ability to display an avatar or photo, after reading this article, you will have the ability to upload the user's photo in AD to display in Outlook, Lync, SharePoint portals and other systems.
I found a similar article (), but it was a long time, decided to revive the topic.
Requirements:
the
Cons:
the
For reference:
the Author is not responsible for any possible damage caused by the materials in this article.
In the article, not the script entirely. The taste and color markers are different.
In fact, my finished script, if the abuse is easier to break Active Directory.
There are several options for uploading photos in AD using PowerShell:
Using the Microsoft PowerShell for Active Directory:
the
Using the Quest PowerShell snap-in for Active Directory:
the
Using the PowerShell snap-in for Exchange:
the
Article based on information from habrahabr.ru
I found a similar article (), but it was a long time, decided to revive the topic.
Requirements:
the
-
the
- staff Photo preferably in JPG format; the file name, it is advisable to standardize; the
- PowerShell and the Active Directory module for PowerShell on a computer; the
- Active Directory Schema needs to be Win 2008 or later (this does not mean the existence of a controller under Window 2008, it is enough to run adprep from Windows 2008 to extend the schema); the
- the User must have rights to change the attributes thumbnailphoto node, jpegPhoto Active Directory (by default, the user can change your photo but the rights can be delegated).
Cons:
the
-
the
- Additional load on support with requests to replace a photo; the
- growth of the Active Directory database NTDS.DIT that can lead to replication problems.
For reference:
the Active Directory Limit the size of the jpegPhoto and thumbnailphoto attribute is 100 KB. The user photo in Outlook 2010 will appear even if you have not installed Exchange, it is enough to have the schema Active Directory Win 2008 or later (This does not mean the existence of a controller under Window 2008, it is enough to run adprep from Windows 2008 to extend the schema). To display the user's photo, in different systems, use different attributes in Active Directory. For example to display in Outlook thumbnailphoto node and to display in SharePoint jpegPhoto.
the Author is not responsible for any possible damage caused by the materials in this article.
In the article, not the script entirely. The taste and color markers are different.
In fact, my finished script, if the abuse is easier to break Active Directory.
Unwilling to learn PowerShell to use it:
finished Active Directory User & computers
There are several options for uploading photos in AD using PowerShell:
Using the Microsoft PowerShell for Active Directory:
the
Import-Module ActiveDirectory
$photo = [byte[]](Get-Content C:\Photo\MyPhoto.jpg -Encoding byte)
Set-ADUser <sAMAaccountName> -Replace @{thumbnailphoto node=$photo}
Set-ADUser <sAMAaccountName> -Replace @{jpegPhoto;=$photo}
Using the Quest PowerShell snap-in for Active Directory:
the
Add-PSSnapin Quest.ActiveRoles.ADManagement
$photo = [byte[]](Get-Content C:\Photo\MyPhoto.jpg -Encoding byte)
Set-QADUser <sAMAaccountName> -ObjectAttributes @{thumbnailphoto node=$photo}
Set-QADUser <sAMAaccountName> -ObjectAttributes @{jpegPhoto=$photo}
Using the PowerShell snap-in for Exchange:
the
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))
Limitation snap-on file size 10 KB. Only replaces the thumbnailphoto node.
Using the PowerShell snap-in for Exchange 2013:
the 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 out 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:
the [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 node"].Clear()
$null = $user.Properties["thumbnailphoto node"].Add($jpg)
$user.CommitChanges()
All of these examples, load the user's photo without changing the size and image quality.
For myself, I decided to use with the Microsoft PowerShell module for Active Directory. But at the first attempt to upload a photo have got the error about failing to load photo from a file size of 5 megabytes. The first idea was to convert the photos, compressing them to a manageable size. But the desire to learn PowerShell won.
So complicate the task of uploading photos. We will add the function of changing the resolution of the photo.
The function takes as input the full path of the file, maximum resolution, the compression quality.
Almost ready feature was found on the Internet and changed for specific tasks.Function resizephoto(){
Param ( [Parameter(Mandatory=$True)] [ValidateNotNull()] $imageSource,
[Parameter(Mandatory=$true)][ValidateNotNull()] $canvasSize,
[Parameter(Mandatory=$true)][ValidateNotNull()] $quality )
# the function takes a file and ouimet it
# check
if (!(Test-Path $imageSource)){throw( "File not found")}
if ($canvasSize-lt 10 -or $canvasSize-gt 1000){throw( "Parameter size should be from 10 to 1000")}
if ($quality-lt 0 -or $quality-gt 100){throw( "quality Setting should be between 0 and 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)
# image resolution after conversion
$canvasWidth = $canvasSize
$canvasHeight = $canvasSize
# Job quality pictures
$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)
#Get the type of pictures
$myImageCodecInfo = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders()|where {$_.MimeType-eq 'image/jpeg'}
# Vyschityvanii multiplicity
$ratioX = $canvasWidth / $bmp.Width;
$ratioY = $canvasHeight / $bmp.Height;
$ratio = $ratioY
if($ratioX -le $ratioY){
$ratio = $ratioX
}
# Create empty pictures
$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)
# Create an empty stream
$ms = New-Object IO.MemoryStream
$bmpResized.Save($ms,$myImageCodecInfo, $($encoderParams))
# cleaning
$bmpResized.Dispose()
$bmp.Dispose()
return $ms.ToArray()
}
Insert this function in the script.
an Excerpt of the main part of the script, set the path to your photo, username, personnel number, full name $PhotoPath = '\\server\FOTO\'
#create a PSDrive to avoid problems with applications to network drives when connected to a snap PSSQL
New-PSDrive -Name Photo-PSProvider FileSystem -Root $PhotoPath
$UserLogin = 'login'
$EmployeeID = '503'
$FullName = 'Full User Name'
# comment out to reduce output
write-host "Processed: `n Username:" $UserLogin "`n number:" $EmployeeID "`n name: "$FullName
# check the conformity of login in AD and external system
$aduser = get-aduser $UserLogin -ErrorAction SilentlyContinue
if ($aduser.name-ne $FullName) {
# if not the same as printing to the screen and do nothing
write-host "in Office" $FullName "`n in ad is " $aduser.name "`nLogin "$UserLogin "`n'n" -ForegroundColor Red
} else {
# assign the EmployeeID in AD from an external system
Set-ADUser $UserLogin -EmployeeID $EmployeeID
$PhotoFile = 'Photo\'+$EmployeeID+'.jpg'
# check that the photo is
If (Test-Path $PhotoFile ) {
# If there is a photo of the employee
# specify the path to the photo and quality
$thumbnailphoto node = [byte[]]( $(resizephoto $PhotoFile 64 80))
$jpegPhoto = [byte[]]( $(resizephoto $PhotoFile 648 80))
# add the photo in thumbnailphoto node
Set-ADUser $UserLogin -Replace @{thumbnailphoto node=$thumbnailphoto node} -ErrorVariable ErrorthumbnailPhoto #-WhatIf
# in case of error
write-host "Error adding the thumbnailphoto node on the login "$UserLogin " ID " $_.autokey
exit
}
# add the photo in the jpegPhoto
Set-ADUser $UserLogin -Replace @{jpegPhoto=($jpegPhoto)} -ErrorVariable ErrorjpegPhoto #-WhatIf
if ($ErrorjpegPhoto -ne $null) {
# in case of error
write-host "Error adding jpegPhoto in the login "$UserLogin " ID " $_.autokey
exit
}
if (!$ErrorthumbnailPhoto -and !$ErrorjpegPhoto) {
# If no errors
# comment out to reduce output
write-host 'Processed...' -ForegroundColor Green
}
} else {
# If there is no photo
Write-Host "Photo" $PhotoFile " for "$UserLogin "not found" -foregroundcolor red
}
}
the Path to the photo set through PSDrive, because after connecting PowerShell PSSQL module to work with MS SQL current path is changed to PS SQLSERVER:\> and accessing network resources without changing folders becomes impossible. Photos are stored on a network share where the file name, personnel number. In the example, removed logging and error handling.
Upload photos from Active Directory:
Some examples to check the correctness of uploading photos to Active Directory.
Using the Microsoft PowerShell for Active Directory:
the Import-Module ActiveDirectory
$user = Get-ADUser <sAMAaccountName> -Properties thumbnailphoto node , jpegPhoto
$user.thumbnailphoto node | Set-Content $env:temp\thumbnailphoto.jpg -Encoding byte
$user.jpegPhoto | Set-Content $env:temp\jpegPhoto.jpg -Encoding byte
Using PowerShell and ADSI:
the $username=$env:username
$domain=$env:userdomain
$temp=$env:temp
$thumbnailphoto node = ([ADSISEARCHER]"samaccountname=$($username)").findone().properties.thumbnailphoto node
if(!($thumbnailphoto node -eq $null)) {$thumbnailphoto node | 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:
the Import-Module ActiveDirectory
Get-ADUser -Filter * -properties thumbnailphoto node | ? {$_.thumbnailphoto node} | select Name
Get-ADUser -Filter * -properties thumbnailphoto node | ? {(-not($_.thumbnailphoto node))} | 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 a photo of the AD in the Windows menu
"Use AD Photos as Windows 7 User Tiles";
"Set the Windows 7 User Tile to AD Thumbnail pic".
Or write your telephone directory titulusdesiderio" "Telephone Directory" with blackjack and photos.
Комментарии
Отправить комментарий