桌面新建一个随机显示桌面.ps1文件,具体代码如下:
# 创建一个目录来存储壁纸
$downloadPath = "$env:USERPROFILE\BingWallpapers"
New-Item -ItemType Directory -Force -Path $downloadPath | Out-Null
# 构建Bing壁纸的URL
$bingURL = "https://www.bing.com"
$bingWallpaperURL = "$bingURL/HPImageArchive.aspx?format=js&idx=0&n=8&mkt=en-US" # 这里获取了最近8天的壁纸
# 发送HTTP请求以获取壁纸信息
$response = Invoke-RestMethod -Uri $bingWallpaperURL
# 解析JSON响应并获取壁纸URL列表
$wallpaperURLs = $response.images.url | ForEach-Object { $bingURL + $_ }
# 随机选择一个壁纸URL
$randomWallpaperURL = $wallpaperURLs | Get-Random
# 使用壁纸URL的哈希值作为文件名
$wallpaperFileName = [System.Security.Cryptography.HashAlgorithm]::Create("MD5").ComputeHash([System.Text.Encoding]::UTF8.GetBytes($randomWallpaperURL)) | ForEach-Object { $_.ToString("x2") }
$wallpaperPath = Join-Path -Path $downloadPath -ChildPath "$wallpaperFileName.jpg"
# 下载壁纸
Invoke-WebRequest -Uri $randomWallpaperURL -OutFile $wallpaperPath
# 设置壁纸
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class Wallpaper {
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
public const int SPI_SETDESKWALLPAPER = 20;
public const int SPIF_UPDATEINIFILE = 0x01;
public const int SPIF_SENDCHANGE = 0x02;
public static void SetWallpaper(string path) {
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
}
}
"@
# 显示壁纸
Invoke-Item $wallpaperPath