top of page
avicoren

How to add Active Directory's User pic in app

Updated: Dec 23, 2021

Do you store users' pictures in Active Directory? If you do, there is nothing easier than putting their pictures in your PowerShell app.

One thing though - the computer that runs this script needs to have Remote Server Administration Tools enabled. More information

It's because we will need ActiveDirectory module installed.

So, here's the thing:


In your Xaml, put any control that can contain a picture. In our example I used a Material Design Chip. That's the Xaml part:

<materialDesign:Chip Name="LeftDrawer_Chip">
    <materialDesign:Chip.Icon>
        <Image Name="LeftDrawer_Chip_Img" />
    </materialDesign:Chip.Icon>
</materialDesign:Chip>

Note that I gave both elements a name, the chip and the picture. That's because I will need both on the code behind.


Next, in your PS script get user's details including the picture

$Account= Get-Aduser -Identity $env:USERNAME -Properties thumbnailphoto

The username will be taken from the environment variable $env:USERNAME. When a user opens a PS session this variable holds her username.

$LeftDrawer_Chip.ToolTip ="$env:USERDOMAIN\$env:USERNAME"

I set a tooltip so when hovering over the chip it will show the domain\username

The $env:USERDOMAIN is the environment variable for the user's domain.

This will put the full name of the user in the chip's text area:

$LeftDrawer_Chip.Content =$Account | Select-Object -ExpandProperty Name

This will save the user's picture in any location you prefer. I always prefer the c:\users\{username}\AppData\Roaming folder, which is $env:APPDATA variable

$Account.thumbnailphoto |
Set-Content "$env:APPDATA\$env:USERDOMAIN-$env:USERNAME.jpg" -Encoding Byte

Don't break the lines. Here it's breaking because of the post's page width.


And finally, the following code will load the image file, making sure it will not be locked in case another session is opened in parallel (Again, don't break lines):

$Bitmap = [System.Windows.Media.Imaging.BitmapImage]::new()
$Bitmap.BeginInit()
$Bitmap.UriSource = "$env:APPDATA\$env:USERDOMAIN-$env:USERNAME.jpg"
$Bitmap.CacheOption = [System.Windows.Media.Imaging.BitmapCacheOption]::OnLoad
$Bitmap.EndInit()
$LeftDrawer_Chip_Img.Source = $Bitmap

... And Voila!


Note - You should put a generic user picture in your Resources\Images folder or use a "user" icon - so it will be displayed in case (1) there is no picture in AD for the user (for example, check if 'thumbnailphoto' is null), and (2) you run the app on a stand alone machine with no Active Directory present. Handle all of those potential errors. On one of my future examples, I will include the entire code for it.

The reason we overwrite the picture each time and don't use an existing one, is because people tend to change their pictures very often these days...


PowerShell is fun!

328 views0 comments

Recent Posts

See All

Comments


bottom of page