Set the Windows 7 user account picture

Not too long ago, I was asked if it's possible and how to set the Windows 7 user account picture (the one you see in the Start menu, and in the Lock screen) using PowerShell.
There is no official documented way of doing it, but it can be accomplished quite easily using the SetUserTile static function from Shell32.dll.

The complete PowerShell example function is:

function Set-AccountPicture {
        [Parameter(Position=0, ParameterSetName='PicturePath')]
        [string]$UserName = ('{0}{1}' -f $env:UserDomain, $env:UserName),

        [Parameter(Position=1, ParameterSetName='PicturePath')]

        [Parameter(Position=0, ParameterSetName='UsePictureFromAD')]
    Begin {
        Add-Type -TypeDefinition @'
        using System; 
        using System.Runtime.InteropServices; 
        namespace WinAPIs { 
            public class UserAccountPicture { 
                [DllImport("shell32.dll", EntryPoint = "#262", CharSet = CharSet.Unicode, PreserveSig = false)] 
                public static extern void SetUserTile(string username, int notneeded, string picturefilename); 
'@ -IgnoreWarnings

    Process {
        if ($pscmdlet.ShouldProcess($UserName, "SetAccountPicture")) {
            switch ($PsCmdlet.ParameterSetName) {

                'PicturePath' {
                    if (Test-Path -Path $PicturePath -PathType Leaf) {
                        [WinAPIs.UserAccountPicture]::SetUserTile($UserName, 0, $PicturePath)
                    } else {
                        Write-Error ('Picture file {0} does not exist!' -f $PicturePath)

                'UsePictureFromAD' {
                    $PicturePath = '{0}{1}_{1}.jpeg' -f $env:Temp, $env:UserDomain, $env:UserName
                    $photo = ([ADSISEARCHER]"samaccountname=$($env:username)").findone().properties.thumbnailphoto
                    $photo | Set-Content -Path $PicturePath -Encoding byte
                    $UserName = '{0}{1}' -f $env:UserDomain, $env:UserName
                    [WinAPIs.UserAccountPicture]::SetUserTile($UserName, 0, $PicturePath)

    End { }

Then, to set a specific picture for a specific user:

Set-AccountPicture -UserName 'CONTOSOmartin' -PicturePath 'C:Tempmartin.jpeg'

or, to set the current logged-on user the picture from his thumbnailphoto attribute in ActiveDirectory:

Set-AccountPicture -UsePictureFromAD –Verbose