DEV Community

Steve Baker
Steve Baker

Posted on • Updated on

Randomizing your Windows desktop background using PowerShell

Hi!

Do you ever get bored of your desktop background? I sure as heck do, so I created a little script to randomize it! (note: this will only work on Windows)

There's 2 files involved:

  • Set-RandomBg.ps1 - my script to download a random image using the WallHaven API
  • Set-Wallpaper.ps1 - a generic module to change the Windows wallpaper which requires an Image file path

Set-RandomBg script

# Specify a search term or leave it blank:
# $keyword=$null
$keyword="pokemon"

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$url = "https://wallhaven.cc/api/v1/search?sorting=random&q=${keyword}";

# See full list of 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
Enter fullscreen mode Exit fullscreen mode

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 of a better or easier way to achieve this, please leave a comment :)

Top comments (1)

Collapse
 
riidom profile image
riidom

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.