Setting the desktop background image via Powershell

UPDATE: 
I found the solution that addressed my problem, which I posted in a post below. Keeping the original post for Internet historical reasons as I the hope this helps someone else later on in their search for a solution. 
===============
I have Bing'ed and I have Google'd and I haven't found a solid answer to setting the desktop wallpaper programmically.  I am trying to do this via PowerShell, but I would be happy for any other language flavor or application to work. 
Below is the code I have tried to set the desktop background image. This has been scrounged from a few sources across the web. This solution works 25% of the time and I haven't figured out what the cause for success or failure of the execution. Or maybe
it's neither, but waiting for Explorer to refresh. The only way to see the change 100% is to log out and log back in.
I am running Windows 8.1 btw. 
Thank you for looking.
Function Get-WallPaper()
$wp=Get-ItemProperty -path 'HKCU:\Control Panel\Desktop\' -name wallpaper
if(!$wp.WallPaper)
{ "Wall paper is not set" }
Else
{"Wall paper is set to $($wp.WallPaper)" }
Function Refresh-Explorer {
$code = @'
private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
private const int WM_SETTINGCHANGE = 0x1a;
private const int SMTO_ABORTIFHUNG = 0x0002;
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern bool SendNotifyMessage(IntPtr hWnd, uint Msg, UIntPtr wParam,
IntPtr lParam);
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SendMessageTimeout ( IntPtr hWnd, int Msg, IntPtr wParam, string lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult );
[System.Runtime.InteropServices.DllImport("Shell32.dll")]
private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
public static void Refresh() {
SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, null, SMTO_ABORTIFHUNG, 100, IntPtr.Zero);
Add-Type -MemberDefinition $code -Namespace MyWinAPI -Name Explorer
[MyWinAPI.Explorer]::Refresh()
Function Set-WallPaper($Value)
echo "Setting background to: $value"
Refresh-Explorer
Set-ItemProperty -path 'HKCU:\Control Panel\Desktop\' -name wallpaper -value $value
rundll32.exe user32.dll, UpdatePerUserSystemParameters
#sleep 1
rundll32.exe user32.dll, UpdatePerUserSystemParameters
#sleep 1
rundll32.exe user32.dll, UpdatePerUserSystemParameters
#sleep 1
Refresh-Explorer
#Stop-Process -ProcessName explorer
NOTE: I left in a few commented out statements. I found that they do not offer any help in formulating a solution.
Thank you.

Great news! I found the solution and all props and credit goes to
jsd1982 of the XKCD comic
forum from a post he made in 2007 and some deep search kung-fu Googling on my part. Here is the
direct link to the post.
This solution has worked for me 100% of the time on Windows 8. The only gotcha I found (minor detail) was when setting this process to run as a scheduled task, I had to run it as elevated privileges for the code to compile in memory. Running this function
from PowerShell at the command prompt was fine. 
NOTE: The code below is a slight trimmed down version posted by jsd1982 to just set the desktop wallpaper. I removed the image fetching from the Internet and the color inversion.
# Credit to jsd1982
function Compile-Csharp ([string] $code, $FrameworkVersion="v2.0.50727",
[Array]$References)
# Get an instance of the CSharp code provider
$cp = new-object Microsoft.CSharp.CSharpCodeProvider
# Build up a compiler params object...
$framework = [System.IO.Path]::Combine($env:windir, "Microsoft.NET\Framework\$FrameWorkVersion")
$refs = new-object Collections.ArrayList
$refs.AddRange( @("${framework}\System.dll",
# "${mshhome}\System.Management.Automation.dll",
# "${mshhome}\System.Management.Automation.ConsoleHost.dll",
"${framework}\system.windows.forms.dll",
"${framework}\System.data.dll",
"${framework}\System.Drawing.dll",
"${framework}\System.Xml.dll"))
if ($references.Count -ge 1)
$refs.AddRange($References)
$cpar = New-Object System.CodeDom.Compiler.CompilerParameters
$cpar.GenerateInMemory = $true
$cpar.GenerateExecutable = $false
$cpar.CompilerOptions = "/unsafe";
$cpar.OutputAssembly = "custom"
$cpar.ReferencedAssemblies.AddRange($refs)
$cr = $cp.CompileAssemblyFromSource($cpar, $code)
if ( $cr.Errors.Count)
$codeLines = $code.Split("`n");
foreach ($ce in $cr.Errors)
write-host "Error: $($codeLines[$($ce.Line - 1)])"
$ce |out-default
Throw "INVALID DATA: Errors encountered while compiling code"
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") > $null
[System.Reflection.Assembly]::LoadWithPartialName("System.Runtime") > $null
# C# code to post to wallpaper
$code = @'
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.IO;
using System.Net;
using Microsoft.Win32;
namespace test
public class Wallpaper
const int SPI_SETDESKWALLPAPER = 20 ;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDWININICHANGE = 0x02;
[DllImport("user32.dll", CharSet=CharSet.Auto)]
static extern int SystemParametersInfo (int uAction , int uParam , string lpvParam , int fuWinIni) ;
public static void SetWallpaper(string uri)
System.IO.Stream s = new WebClient().OpenRead(uri);
Image img = System.Drawing.Image.FromStream(s);
Bitmap copy = new Bitmap(img.Width, img.Height);
Graphics g = Graphics.FromImage(copy);
Rectangle rect = new Rectangle(0, 0, img.Width, img.Height);
g.DrawImage(img, rect, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
g.Dispose();
img.Dispose();
// Save to a temp file:
string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
copy.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp);
RegistryKey key = Registry.CurrentUser.OpenSubKey( @"Control Panel\Desktop", true ) ;
key.SetValue(@"WallpaperStyle", 1.ToString( ) ) ;
key.SetValue(@"TileWallpaper", 0.ToString( ) ) ;
SystemParametersInfo( SPI_SETDESKWALLPAPER,
0,
tempPath,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE );
function Set-Wallpaper([string] $imgurl)
compile-CSharp $code
[test.Wallpaper]::SetWallpaper($imgurl)

Similar Messages

  • Is there an ARD command or Unix command that I can send to reset the desktop background image to default?

    I was forced to create a local user with an automatic login on all of the machines in the building. I listed off many various issues that could come arise by doing this but was tuned out. Now people are changing all of the desktop backgrounds to some pretty inappropriate images. I forewarned the person ordering this that this may be one of the many issues that would arise when doing away with our server based logins, and now I am charged with fixing every desktop every time someone changes it to something inappropriate.
    Is that an Apple Remote Desktop command or a Unix command that I can send through ARD v3.5.3 to the machines to reset the desktop background image to the default Aqua Blue jpeg image located in the /MacintoshHD/Library/Desktop\ Pictures/Aqua\ Blue.jpg.
    The machines that I am dealing with have OS X 10.4.11, OS X 10.5.8, OS X 10.6.8, and OS X 10.7.4 installed on them, but the OS X 10.4.11 machines are the ones that are creating the biggest issue so I would like to deal with those first.

    Ya, I'd love to have the computers connected to the Xserver, unfortunately against my heeding, I was ordered to take them off of the Xserver, so they only have a local account that automatically logs in on startup, and even though I have Parental Controls set, I can not stop them from going to Safari, selecting an inappropriate image and setting it as the background, so now I’ve been ordered to fix all of the backgrounds that people are messing with.
    My Xserver is running OS X 10.4.11 Server Edition. Yes, I would love a new server, but that’s not happening due to budget cuts.
    So what I am hoping for is a command that I can put into Apple Remote Desktop v3.5.3 and push out to all of the computers via its Unix commands and reset all the desktops to their default image.

  • Set the custom background images to default?

    Is there any way to set the custom background image to default instead of manually changing the background image in the phone?

    This was actually discussed some time ago. Please see this link.
    http://www.voipintegration.com/software.html
    See discussion here:
    http://forums.cisco.com/eforum/servlet/NetProf?page=netprof&forum=Unified%20Communications%20and%20Video&topic=IP%20Telephony&CommCmd=MB%3Fcmd%3Dpass_through%26location%3Doutline%40^1%40%40.1ddd4505

  • How do I set the desktop background to automatically change every so often?

    I had my desktop background set to change every five seconds, with the photos coming from a folder in my iPhoto files. I then made a new folder of background pictures in iPhoto, but when I switched to them and tried to make it "change every 5 seconds", or 1 minute etc., it would not change. I then reverted back to the original group of files and it STILL wouldn't change, even though it had been doing so for the many months that I had been using this set of background photos before.
    I have clicked on "change every 5 seconds" and "random order", but for some reason I can now only change the pictures manually by clicking on them in the right hand pane of the system preferences window. Please can someone tell me how to make them change automatically again...?

    Have you tried restarting your computer and attempting it again?
    Sorry if this is a dumb question, but a lot of people run their machines 24/7 and sometimes a little reboot helps.

  • How to block changes of desktop background image

    I manage a 30-computer Mac lab in a public high school and I would like to prevent users from changing the desktop background image.
    As far as I know, there are two ways to change the desktop background image: through System Preferences and by right-clicking an image and selecting Set Desktop Picture.
    Blocking System Preferences is easily done through Parental Controls.
    But how do I prevent the right-click, Set Desktop Picture method of changing the desktop image?
    You can imagine the kinds of images that end up as desktop backgrounds in a high school computer lab.

    You might try going to System Preferences > Keyboard > Keyboard Shortcuts. In the left pane select Services, then uncheck the item "Set Desktop Picture" under Pictures in the right pane. Once that's done, block that prefs pane.

  • I belong to a graphic site dreamies.de and my images are disappearing from there since I right clicked on what I thought was set as desktop background. There wa

    I belong to a graphic site dreamies.de and my images are disappearing from there since I right clicked on what I thought was set as desktop background. There was another entry under it that said block images from dreamies.de. That is the one that I clicked on by accident and no one knows how to reverse it. Does anyone here know how to reverse it? I was using firefox 3.6 beta 3 when this happened. I am now on firefox 12.
    I already tried right-click the page, choose View Page Info, then click Permissions. The first item is the site-specific permission for images and you should be able to reset back to the default here. This did not work.
    I also tried right-click View Page Info and click Media. Click the first image on the list and observe the Block Images checkbox above the preview at the bottom. Arrow down the list until you come to a site that is blocked and unblock it. There was no unblock just a delete, so I deleted it. This did not work either.
    I know it is a firefox issue because the images are all there when I log in using Internet explorer, but on firefox there are many of my images missing.

    This is the question that I need an answer to:
    I belong to a graphic site dreamies.de and my images are disappearing from there since I right clicked on what I thought was set as desktop background. There was another entry under it that said block images from dreamies.de. That is the one that I clicked on by accident and no one knows how to reverse it. Does anyone here know how to reverse it? I was using firefox 3.6 beta 3 when this happened. I am now on firefox 12.
    I already tried right-click the page, choose View Page Info, then click Permissions. The first item is the site-specific permission for images and you should be able to reset back to the default here. This did not work.
    I also tried right-click View Page Info and click Media. Click the first image on the list and observe the Block Images checkbox above the preview at the bottom. Arrow down the list until you come to a site that is blocked and unblock it. There was no unblock just a delete, so I deleted it. This did not work either.
    I know it is a firefox issue because the images are all there when I log in using Internet explorer, but on firefox there are many of my images missing.

  • How do I set the desktop wallpaper with an image in aperture 3?

    Sorry for the silly question, but I can't find how to set my desktop wallpaper with an image in aperture 3. It was simple when using Iphoto, but I can't find the method in aperture.
    Thanks,
    Dale.

    Command(⌘)-9 is no longer listed in the list of default keyword shortcuts, and it has no effect.
    I wrote a little Automator service to bring the Command(⌘)-9 back.
    A copy of this service is here for download:
    http://dreschler-fischer.de/scripts/SetDesktopPicture.workflow.zip
    This service uses three actions:
    Aperture: Get selected images
    Export Masters
    Finder: Set the Desktop Picture
    To install it, open the workflow in Automator and save it as service.
    To use it, select any image in Aperture, then activate the service from the Aperture menu -> Services, and it will set the master of the selected image as Desktop picture.
    If you like, you can assign the Command(⌘)-9 key to the service (in the System Preferences -> Keyboard -> Keyboard Shortcuts Panel) and then  turn any image you selected into Desktop wallpaper by simply pressing (⌘)-9.
    @Frank Caggiano, if you are still following this thread: for some reason this workflow succeeds with exporting the master, but I could not get it to work with the versions instead. Any ideas?
    Caution: this service will clutter the Desktop with the exported images. If you want to avoid that, change the export action to export the image to a different folder.
    Regards
    Léonie

  • How can I set the desktop image for client computers?

    How can I set the desktop image for client computers using ARD or terminal?

    How can I set the desktop image for client computers using ARD or terminal?

  • When viewing some websites my desktop background image shows as the page background...why...and how do I fix this?

    It seems that the current version of Firefox does not understand how to process style sheets. Instead of the stylesheet background color or image, I am now seeing my PC's desktop background image. This does not happen with IE or Chrome. When checking the error console, I get "Warning: Unknown property 'zoom'. Declaration dropped. Source File: http://trustserve.net/themes/ModernBlue/templates_cached/EN/global.css Line: 4"
    I am not trying to zoom.
    Any ideas on how to fix this. I can't use Firefox with these problems and I really liked it prior to these problems.

    I thought I had it disabled. I enabled aero and then disabled to be sure, and still have the problem, but that was a very good idea. Thanks.
    The problem started shortly after I installed two new programs, a graphics program, and an anti-virus. I just removed both programs and restarted the computer and that seems to have solved the problem. Your idea about Aero gave me the idea that one, or both of these programs changed some of my system settings. I am now going to install them, one at a time, and see if the transparency problem returns. I'll post my findings.

  • I am using Firefox 3.5.9 in Linux Gnome and need to remove the "Set As Desktop Background" from the right click menu or at least disable the users ability to change it from Firefox as I am running a kiosk.

    USeing Suse Linux Enterprise Desktop 11SP1 with gnome desktop and Firefox 3.5.9. I have created a firefox user profile and need to remove or restrict the ablitiy of the users to change the desktop background.

    See http://kb.mozillazine.org/Chrome_element_names_and_IDs
    Add the code to [http://kb.mozillazine.org/UserChrome.css userChrome.css] below the @namespace line.
    <pre><nowiki>#context-setDesktopBackground {display:none!important;}
    </nowiki></pre>
    See also http://kb.mozillazine.org/Editing_configuration

  • How do I extract a theme background and set it as the desktop background?

    Hi
    I want to have the industrial theme background as the desktop background.
    I have tried unpacking the keynote application but end up with Industrial_1920x1080.kth
    How do I convert a kth file into a recognisable graphics file?
    Thanks
    AJ

    If you mean that you want to use the Moroccan background in Pages, yes the same principle applies. the Keynote "package" is simply the Keynote application -- Control-Click on the Keynote icon in the Finder, then choose "Show Package Contents" from the pop-up menu. In the new Finder window that appears, follow the directions as outlined above. Be careful not to move or delete any files in the package.

  • Desktop Background Images Dithering

    All of my desktop background images have been dithering, despite the fact that my display is set to 32-bit color. This can be demonstrated by opening up the image used for the desktop in an image-editing application and viewing them both side-by-side. Here's a screenshot of such a comparison:
    This is a major bummer - anyone have an idea what is wrong?

    I should have mentioned that the dimensions of the background image exactly match the resolution of the monitor (1280x1024).
    Also, yes, it is an LCD monitor, but it is hooked up via DVI.
    I am wondering if it might have to do with the display card hardware (GeForce FX 5200), as I did not have this problem under the same circumstances, in tiger, but under different hardware...
    So, no, still not solved - but thanks for your input.

  • How do I disable "Set as Desktop Background" as an option in Firefox 3.6 running on Mac OSX 10.5?

    I'm trying to disable the "Set as Desktop Background" option for Firefox 3.6 in a Mac OSX 10.5 environment. I have a default image that I want as the background on my desktop and I don't want it to be changed.

    See http://kb.mozillazine.org/Editing_configuration#How_to_edit_configuration_files
    Add code to [http://kb.mozillazine.org/UserChrome.css userChrome.css] below the @namespace line.
    <pre><nowiki>@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); /* only needed once */
    #context-setDesktopBackground {display: none !important;}</nowiki></pre>

  • Whenever I shutdown my mac book pro the desktop background changes. How can I fix this?

    Please help

    If you log in automatically, a bug in some versions of OS X will cause the desktop picture to revert to the default image at every startup. The only known workaround is to disable automatic login in the Users & Groups preference pane.
    If the selected Desktop picture is stored in an iPhoto library on an external drive, export it from iPhoto and move it to a folder on the startup volume. (Credit for this solution to ASC member janay.)
    If the desktop picture always reverts to a plain blue background, one of your login items may be causing the problem. The "TeamViewer" application can have this effect; see this thread. If it's not that in your case, rule out all other third-party login items as possible causes.
    If you have a MacBook Pro model with automatic graphics switching, disable it temporarily in the Energy Saverpreference pane, set the Desktop picture, then reboot and re-enable graphics switching.
    If none of the above applies to you, proceed as follows.
    Back up all data.
    In the Finder, hold down the option key and select
    Go ▹ Library
    from the menu bar. From the Library folder, delete the following item, if it exists: 
    Caches/com.apple.systempreferences
    and move the following items to the Desktop, if they exist:
    Application Support/Dock/desktoppicture.db
    Preferences/com.apple.desktop.plist
    Launch System Preferences and test. If you still have the issue, put the items you moved to the Desktop back where they came from and post again. Otherwise, delete the items.

  • How do I keep the body background-image centered?

    I have a body background-image that does not fill up the
    entire window on the tops and bottoms of most monitors (it
    strectches to the left and right just fine) and so I would like to
    have it centered vertically with equal amounts of the
    background-color #ECE5C8.
    I assumed using background-position: 50% 50% would do the
    trick and it does until switching to full screen mode and all the
    content jumps upwards and messes up the whole site layout (IE
    only-in friefox, the background-image still doesn't center) so
    instead I have the background-position set to: 50% 0%.
    Thanks a million to anyone who can help me get it centered, I
    know there has to be an easy fix but I sure can't figure it out!
    The site can be found here:
    http://www.lightspacewebdesign.com/sacredsolas

    There would be only two ways to make this layout 'work'.
    1. Just make everything on that page a graphic. Then there is
    no
    possibility that resizing the text in the browser will blow
    the layout.
    This is a very bad idea for obvious reasons.
    2. Have the text containing 'graphical box' built in pieces
    so that as the
    text expands, it can cause the box to expand as well. The
    easiest way to do
    this is with a top a middle and a bottom image of the box,
    using each as the
    background image of three stacked containers. Place the text
    in the middle
    container and as it expands, it will tile the middle
    background image
    vertically to give the impression of the box expanding. This
    approach
    doesn't lend itself to your background image, since there is
    no way to tile
    the background image to fill the newly created space.
    Beyond that, I think you are a dead duck. The problem is not
    that this is
    what you were given to work with - it's that you didn't
    understand how
    unusable the design was when you accepted it. I think your
    best option now
    is to go back to the designer and explain to them how this
    lovely layout
    only works well in print, and not on the web. Show them how
    it fails.
    Solicit suggestions from them for how to make it work in a
    medium where
    there is no way to control the size of the text.
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================
    "afriendofcheese" <[email protected]> wrote
    in message
    news:[email protected]...
    > By "a rigid layout scheme that cannot allow flexibility"
    I assume you mean
    > that
    > everything shouldn't be bound inside the position of the
    background-image,
    > but
    > this is what the designer and client gave me to work
    with.and so I have to
    > make
    > due.
    >
    > With that in mind, I hope someone out there can help me
    out with this!
    >

Maybe you are looking for

  • 3.0.1 question

    So here's something very weird... While Numbers 3.0.0 was able to export into Numbers '09 successfully, the 3.0.1 version doesn't. It looks like it's going through the motions, but then pops up with a 'this file cannot be saves as 'name of file'' and

  • How Many Times in a Week Will Apple Keep Locking My Account?

    Twice a week Apple keeps locking my account and I have to go reset it with my old password or issue a new password.  I have done both yet I can't go a week without being told I have to do it again...and again. How do I end this loop?

  • What's the highest quality iphone 5 wireless headphone solution?

    Is there a better solution than an aptx dongle on my iphone 5 paired with aptx headphones? the information out there is confusing, like apple supports AAC, bluetooth supports AAC, but is there such a thing as using AAC bluetooth with say spotify? or

  • Compressing Folders, Missing Files

    I routinely zip up (Compress) the contents of a particular folder. I've noticed that sometimes newly created files do not get included in the resulting .zip file. However if I use Finder to view the subdirectory that contains the new file, the new fi

  • Query about database

    Can Oracle support graphic? I need a database that can store text information and image inside its database.