Hi!
Tired of the same desktop background? Here's a small PowerShell script that pulls a random wallpaper from WallHaven's free API and sets it every time Windows starts
Note: this will only work on Windows.
There are 2 files involved:
- Set-RandomBg.ps1 - downloads a random image using the WallHaven API
- Set-Wallpaper.ps1 - a reusable module to change the Windows wallpaper which requires an image file path
Set-RandomBg script
# You can specify a search term here or leave it blank:
# $keyword=$null
$keyword="nature"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$url = "https://wallhaven.cc/api/v1/search?sorting=random&q=${keyword}";
# See full list of API options here:
# https://wallhaven.cc/help/api#search
"Loading results from: $url"
$response = Invoke-RestMethod -Uri $url
# Filter out landscape results
$response.data = $response.data | Where { $_.dimension_y -le $_.dimension_x }
$count = $response.data.length -1
"Found $count images"
$random = Get-Random -Minimum 0 -Maximum $count
"Random id: $random"
$wallUrl = $response.data[$random].path
$filename = "C:\temp\bg.jpg"
"Downloading $filename"
Invoke-WebRequest $wallUrl -OutFile $filename
# load the Set-Wallpaper module so we can execute it
. $PSScriptRoot/Set-Wallpaper.ps1
Set-Wallpaper -Image $filename
# To debug any issues, uncomment the following line:
# pause
Set-WallPaper script
The Set-WallPaper script looks a little scary at first but all it's doing is changing the Windows desktop wallpaper setting via C# (there's no PowerShell way and alternative methods like updating the Registry wouldn't work for me)
The script can be found here:
https://www.joseespitia.com/2017/09/15/set-wallpaper-powershell-function/
Running via start-up
To run this script on start-up, create a new Shortcut in your startup folder located at shell:startup with the following TargetPath
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe " -file C:\MYSCRIPTSFOLDER\Set-RandomBg.ps1. Make sure to replace MYSCRIPTSFOLDER with the location of the PowerShell scripts!
Thanks for reading! If you know a better way to achieve this, or want to
extend it (WallHavens API supports multiple filtering options), leave a comment below.
Top comments (1)
Win10 has a built-in function for changing desktop backgrounds. I have W10 at work in office and can't look where exactly you do that right now, but AFAIR in the settings, you can say "pick from folder" instead of specifying a single image.
But it may act slightly different than your script does, especially wrt 2 monitors.