Getting photos of colleagues from Active Directory in PowerShell

PowerShell has been around now for more than a decade. During this decade, I learned it at least 3 times. Actually, I’ve always liked the concept but I felt a little bit uncomfortable with the syntax.

Last week, I wanted to get portrait pictures of my colleagues for an overview I was working on. And the moment I realized that we have images only available in the Active Directory (AD), I decided to give PowerShell another try. Since PowerShell ISE feels like Windows Vista, I decided to try Visual Studio Code with PowerShell language support extension. I was very pleasantly surprised by its capabilities, it removed all uncomfortable feelings from the syntax.

The first step before you start querying Active Directory with PowerShell is to verify if you have the ActiveDirectory module imported. You can do it by calling the following command:

Get-Module ActiveDirectory

If you are running Windows 10 like I am, you probably don’t have it, but you can obtain it by installing Remote Server Administration Tools for Windows 10 (KB2693643). I like to install my Windows software with Chocolatey, nevertheless in this case Chocolatey package seemed to be broken, so I installed KB2693643 directly from Microsoft Download Center.

By the way, you can verify a successful installation by calling

Get-HotFix KB2693643

The last step before starting to explore AD is to call

Import-Module ActiveDirectory

After that, the writing script was quite straightforward. It took me approximately 15 minutes. The only trick was to ask for thumbnailPhoto property of ADUser explicitly.

param ($ADGroupName, $TargetDir)

Get-ADGroupMember $ADGroupName -Recursive | 
    Get-ADUser -Properties SamAccountName, thumbnailPhoto |
    Where-Object { $_.thumbnailPhoto.Length -gt 0 } |
    ForEach-Object { 
        Set-Content -Path ($TargetDir + $_.SamAccountName + ".jpg") -Value $_.thumbnailPhoto -Encoding Byte

Be free to use this snippet as you wish and don’t forget to share you experience.