Wednesday, March 14, 2018

Setting the lock screen background with PowerShell

There's no simple Registry value holding the path to the image used as the lock screen background for a given user (not counting the policy one that only works on Enterprise/Education). To automate setting the current user's lock screen background, you can use PowerShell!
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
Function Await($WinRtTask, $ResultType) {
 $asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
 $netTask = $asTask.Invoke($null, @($WinRtTask))
 $netTask.Wait(-1) | Out-Null
 $netTask.Result
}
$tStorageFile = [Windows.Storage.StorageFile,Windows.Storage,ContentType=WindowsRuntime]
$img = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($path) $tStorageFile
[Windows.System.UserProfile.LockScreen,Windows.System.UserProfile,ContentType=WindowsRuntime] | Out-Null
[Windows.System.UserProfile.LockScreen]::SetImageFileAsync($img)

The Await function used here appeared previously on this blog -- it allows PowerShell code to await and get results from WinRT tasks. The rest of the script is a straightforward application of the relevant WinRT APIs. First a StorageFile is opened from the $path specified, then it's used to set the lock screen image.

3 comments:

  1. Hello. I am about to write a script which will change lockscreen image.
    I found out what you wrote here is pretty helpful. But i do still have no idea what next i should do.
    Can you help to update this script to make it a executable script?
    Thank you in advance.

    ReplyDelete
    Replies
    1. Check out Set-Screen on powershell gallery. It works on 10 Pro. Just be sure to first set the lockscreen as picture mode so you don't have spotlight tips and feeds on your lockscreen. Not sure why ms decided to disable this feature for 10 Pro. The script creates some registry entries and uses Personalizaton CSP to apply the lock screen.

      Delete
    2. Hi, thanks - works on win10 2004

      But I had to add missing ")" where you declare $img :)

      Delete