Categories
IT

Set Windows 10 background slideshow script in Powershell

I have set with every installation of Windows 10 with my profile a slideshow to change picture from a folder every X minutes. However recently I noticed that this resets from time to time and goes to one picture / slideshow over only some of the pictures that Windows has decided to keep in it’s cloud cache.

Thinking it should be easy I looked around for solutions but found out it is not that trivial (doh it is after all Microsoft 🙂 ). Finally seem to have something workable in Powershell below which you can add to startup (%userprofile%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup) e.g. by using a batch file that runs the poweshell script:

@rem save as a *.cmd file (add shortcut to it in startup)
@echo off
powershell .\set-slideshow.ps1
# to use this, need to create a good slideshow setup from a folder then copy the files from $dest to $source
$source = "$env:userprofile\Install\MySoft\pws\slideshow"
$dest = "$env:appdata\Microsoft\Windows\Themes"

$id = get-random
$code = @"
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Threading;
namespace Wallpaper {

   public class Setter$id {
      public const int SetDesktopWallpaper = 20;
      public const int UpdateIniFile = 0x01;
      public const int SendWinIniChange = 0x02;

      [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
      private static extern int SystemParametersInfo (int uAction, int uParam, string lpvPara, int fuWinIni);

      public static void SetWallpaper (string path) {
         SystemParametersInfo(SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange);
      }

      public static void SetSlideshow (string path) {
         RegistryKey keyz = Registry.CurrentUser.OpenSubKey("Control Panel\\Personalization\\Desktop Slideshow", true);
		 //enable shuffle
		 keyz.SetValue(@"LastTickHigh", 0);
 		 keyz.SetValue(@"LastTickLow", 0);
		 //set to 10 minutes shuffle slideshow
		 keyz.SetValue(@"Interval", 600000);
		 keyz.SetValue(@"Shuffle", 1);
		 keyz.Close();
		 
         keyz = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
         //"Fit" style
         keyz.SetValue(@"WallpaperStyle", "10");
         keyz.SetValue(@"TileWallpaper", "0");
		 keyz.Close();
         SystemParametersInfo(SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange);
		 //Thread.Sleep(20000);
      }
	  
   }
}
"@

Copy-item -Path "$source\*" -Destination $dest -Force
# don't know how and why but setting it to empty string makes shuffle working (nonexist.jpg attempt does not although it does set to a color background)
#[Wallpaper.Setter]::SetWallpaper("c:\nonexist.jpg")
Add-Type -TypeDefinition $code -Language CSharp
Invoke-Expression "[Wallpaper.Setter$id]::SetWallpaper('')"
Invoke-Expression "[Wallpaper.Setter$id]::SetSlideshow('$dest\TranscodedWallpaper')"
#Stop-process -name explorer