LuckyFalkor84
LuckyFalkor84

Reputation: 607

How to change the desktop background with Powershell consistently

I am trying to change the desktop background with Powershell. I had been trying to use the following code which only works some of the time.

Remove-ItemProperty -path "HKCU:\Control Panel\Desktop" -name WallPaper -Force
Set-ItemProperty -path 'HKCU:\Control Panel\Desktop\' -name Wallpaper -value $wallpaper -Force
RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True

I had tried a number of other variations on this code like adding delays with Start-Sleep or using Start-Job {RUNDLL32.EXE ...} then Wait-Job.

I am guessing it is some sort of weirdness with trying to use RUNDLL32.exe. I am running Windows 7 32bit with Powershell V5.

Curious side note, I run the same code in Powershell V6 on the same computer and the code runs flawlessly every time. Any idea as to why that might be and how I might be able to get it to work consistently on Powershell V5?

Upvotes: 0

Views: 5491

Answers (1)

Theo
Theo

Reputation: 61168

You could try using the SystemParametersInfo function of user32.dll like this:

Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
public class Wallpaper {
    public const uint SPI_SETDESKWALLPAPER = 0x0014;
    public const uint SPIF_UPDATEINIFILE = 0x01;
    public const uint SPIF_SENDWININICHANGE = 0x02;
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    private static extern int SystemParametersInfo (uint uAction, uint uParam, string lpvParam, uint fuWinIni);
    public static void SetWallpaper (string path) {
        SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
    }
}
'@


$wallpaper = 'X:\pictures\mywallpaper.jpg'  # absolute path to the image file
[Wallpaper]::SetWallpaper($wallpaper)

Upvotes: 1

Related Questions