Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save Hiryuto-oecu/b1581e17026eba25a2c1f0ea51c253dd to your computer and use it in GitHub Desktop.

Select an option

Save Hiryuto-oecu/b1581e17026eba25a2c1f0ea51c253dd to your computer and use it in GitHub Desktop.
Set Random Lock Screen Wallpaper from a Folder

Set Random Lock Screen Wallpaper from a Folder

This PowerShell script automatically sets a random image from a user-specified folder as the Windows lock screen wallpaper. It uses modern Windows Runtime APIs for robust performance and does not require administrator privileges.

Features

  • No Admin Rights Needed: Runs safely under a standard user account.
  • Random Image Selection: Automatically picks a random image (.jpg, .jpeg, .png) from your chosen folder.
  • Detailed Logging: Creates a log file (LockScreen_Log.txt) in your Documents folder. This file records every step of the process, making it easy to troubleshoot any issues.
  • Path Validation: Checks if the specified image folder exists before attempting to read from it.
  • Error Handling: Provides clear error messages in the log file if no images are found or if something goes wrong.
  • Modern API Usage: Utilizes the Windows.System.UserProfile.LockScreen API for a reliable and officially supported way to change the lock screen on Windows 10 and 11.

How to Use

Follow these steps to get the script up and running.

Step 1: Configure the Script

  1. Open the script file in a text editor (like Notepad, VS Code, etc.).

  2. Locate the following line at the top of the script:

    $imageFolder = "Paste the file path containing the image here."
  3. Replace "Paste the file path containing the image here." with the absolute path to the folder where your images are stored.

    Example:

    $imageFolder = "C:\Users\MyUser\Pictures\Wallpapers"

    or

    $imageFolder = "D:\My Photos\Favorites"

Step 2: Save the Script

Save the file with a .ps1 extension. A recommended name is Set-RandomLockScreen.ps1.

Step 3: Run the Script

You can run this script directly without needing administrator rights.

  1. Right-click the script file (Set-RandomLockScreen.ps1).
  2. Select "Run with PowerShell".

Alternatively, you can open a standard PowerShell window and run the script from there:

# Navigate to the directory where you saved the script
cd C:\Path\To\Your\Script

# Run the script
.\Set-RandomLockScreen.ps1

Execution Policy

If you encounter an error stating that scripts are disabled on your system, you may need to change the PowerShell execution policy. You can do this by running the following command in a PowerShell window:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Answer Y (Yes) when prompted. This command allows locally saved scripts to run.

About the Log File

The script creates and updates a log file each time it runs. This is very useful for confirming that the script ran successfully or for diagnosing problems.

  • Log File Location: C:\Users\<Your-Username>\Documents\LockScreen_Log.txt
  • Successful Run: If everything works, the log will show which image was selected and a "SUCCESS" message at the end.
  • Errors: If an error occurs (e.g., folder not found, no images), the log will contain detailed error messages that can help you identify the cause.

Requirements

  • OS: Windows 10 / Windows 11
  • PowerShell: v5.1 or later

This README was created by gemini-2.5-pro

About Questions

If you have any questions about this program, please post them in the comments of this gist. I may not be able to reply immediately, but I will respond as soon as I notice them.

# --- Configuration ---
# --------------------------
# Replace the path after `$imageFolder` with the absolute path to the folder containing the images you want to set as your lock screen background.
# Example: C:\Users\user-name\Pictures
# --------------------------
$imageFolder = "Paste the file path containing the image here."
$logPath = "C:\Users\$env:USERNAME\Documents\LockScreen_Log.txt"
# --- Script Body ---
Function Write-Log {
param ([string]$Message)
"$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $Message" | Add-Content -Path $logPath
}
# Clear previous log content
Clear-Content $logPath -ErrorAction SilentlyContinue
Write-Log "Script execution started."
# Folder existence check
if (-not (Test-Path $imageFolder -PathType Container)) {
Write-Log "ERROR: The specified folder was not found: $imageFolder"
exit
}
Write-Log "Image folder found: $imageFolder"
# Get random image
$imageFile = Get-ChildItem -Path $imageFolder -Include *.jpg, *.jpeg, *.png -Recurse | Get-Random
if (-not $imageFile) {
Write-Log "ERROR: No image files were found in the specified folder."
exit
}
Write-Log "Random image selected: $($imageFile.FullName)"
# Load Windows Runtime APIs
try {
Write-Log "Attempting to load Windows Runtime APIs..."
[Windows.System.UserProfile.LockScreen,Windows.System.UserProfile,ContentType=WindowsRuntime] | Out-Null
[Windows.Storage.StorageFile,Windows.Storage,ContentType=WindowsRuntime] | Out-Null
Add-Type -AssemblyName System.Runtime.WindowsRuntime
Write-Log "Windows Runtime APIs loaded successfully."
} catch {
Write-Log "FATAL ERROR: Failed to load Windows Runtime APIs."
exit
}
# Prepare .NET helper components
Write-Log "Preparing .NET helper components..."
$asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.IsGenericMethod -and ($_.GetParameters().Count -eq 1) -and ($_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1') })[0]
$asTaskAction = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and !$_.IsGenericMethod -and ($_.GetParameters().Count -eq 1) -and ($_.GetParameters()[0].ParameterType.Name -eq 'IAsyncAction') })[0]
if ($null -eq $asTaskGeneric -or $null -eq $asTaskAction) {
Write-Log "FATAL ERROR: Failed to find required .NET helper methods ('AsTask')."
exit
}
Write-Log ".NET helper components prepared successfully."
# Define helper functions
function Await($WinRtTask, $ResultType) {
$asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
$netTask = $asTask.Invoke($null, @($WinRtTask))
$netTask.Wait(-1) | Out-Null
$netTask.Result
}
function AwaitAction($WinRtAction) {
$netTask = $asTaskAction.Invoke($null, @($WinRtAction))
$netTask.Wait(-1) | Out-Null
}
Write-Log "Helper functions defined."
# --- Set lock screen wallpaper ---
try {
Write-Log "Attempting to get StorageFile object for the image..."
$storageFile = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($imageFile.FullName)) ([Windows.Storage.StorageFile])
Write-Log "StorageFile object obtained successfully."
Write-Log "Attempting to set the image on the lock screen..."
AwaitAction ([Windows.System.UserProfile.LockScreen]::SetImageFileAsync($storageFile))
Write-Log "SUCCESS: Lock screen wallpaper was set successfully."
}
catch {
Write-Log "FATAL ERROR: An exception occurred during the final stage."
$currentException = $_.Exception
$indent = " "
while ($null -ne $currentException) {
Write-Log "$($indent)Exception Type: $($currentException.GetType().FullName)"
Write-Log "$($indent)Exception Message: $($currentException.Message)"
if ($currentException -is [System.AggregateException]) {
Write-Log "$($indent)--> Unwrapping AggregateException:"
foreach ($innerEx in $currentException.InnerExceptions) {
Write-Log "$($indent) --> ROOT CAUSE: $($innerEx.GetType().FullName) - $($innerEx.Message)"
}
}
$currentException = $currentException.InnerException
$indent += " "
}
}
@AcousticVibe
Copy link

AcousticVibe commented Jan 20, 2026

Hello!

The script works perfectly. Is there a way to automatically run it at specific intervals or any time you are signed out?

Thanks :)

Edit: nvm, I just found out about task scheduler. Thanks for the script though.

@Hiryuto-oecu
Copy link
Author

Thanks for the first comment!

​I found a few other Gists doing similar things, but they didn't work for me. That's why I created this one and decided to post it for anyone else who might need it.

I'm happy it worked out for you!

@AcousticVibe
Copy link

You’re welcome!

I’ve literally spent hours on two separate days trying to find a way to randomly change the Lock Screen. Such a basic customisation option and Microsoft doesn’t have it.

Now I can sleep in peace. 😎

@aoloe
Copy link

aoloe commented Jan 24, 2026

Thanks for sharing!

Worked well for me on Windows 11.

Here a little contribution from my side: the instructions for triggering this script at each unlock.

If you want a fresh image each time the lock screen is activated:

  • Open the "Task Scheduler"
  • Create a new task
  • Set it to be triggered at unlock (Triggers tab)
  • Set the action (Actions tab) to:
    • Program/Script: conhost.exe
    • Arguments: --headless Powershell.exe "C:<path to the script>\Set-RandomLockScreen.ps1"
    • Remark: conhost.exe is a "a Windows process that manages console windows like Command Prompt and PowerShell, enhancing user interaction and system security" and has a --headless option (otherwise a Powershell flashes / gets opened)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment