每日自动更新 bing 壁纸

本贴最后更新于 409 天前,其中的信息可能已经时移世异

该脚本仅在 win10 下测试通过

<#

.Synopsis
   自动设置bing图片为桌面壁纸
.DESCRIPTION
   添加计划任务,可每日自动更新并设置bing图片为壁纸,并且在图片下添加图片标题及版权文字
.EXAMPLE
    必应每日壁纸.ps1 
    必应每日壁纸.ps1 [-Task]
.INPUTS
   到此 cmdlet 的输入(如果有)
.OUTPUTS
   来自此 cmdlet 的输出(如果有)
.NOTES
   一般注释
.COMPONENT
   此 cmdlet 所属的组件
.ROLE
   此 cmdlet 所属的角色
.FUNCTIONALITY
   最准确描述此 cmdlet 的功能
#>
[CmdletBinding(DefaultParameterSetName)] # 设置默认参数组为空
Param(
    [Parameter(ParameterSetName="Task")]
    [switch]$Task,
    [Parameter(DontShow,ParameterSetName="None")]
    [switch]$None
)

if ($task)
{
    $tem=Get-ScheduledTaskInfo -TaskName "每日自动更换bing壁纸" -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
    if ($tem)
    {
        Write-Error -Message "该计划任务已经存在"

    }
    else
    {
        # 任务操作   程序 ,工作目录,参数
        $A = New-ScheduledTaskAction -Execute "PowerShell"  -WorkingDirectory "$($PSScriptRoot)" -Argument "$($Script:MyInvocation.InvocationName)"
        # 触发器    每天零点一秒 在六小时内随机
        $T = New-ScheduledTaskTrigger -Daily -At 0:0:1  -RandomDelay 6:0:0          
        # 创建者  当前用户名
        $P = New-ScheduledTaskPrincipal "$env:userdomain\$env:username" 
        # 设置集   各种相关设置
        $S = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -WakeToRun -Priority 4 -DontStopIfGoingOnBatteries -DontStopOnIdleEnd -RunOnlyIfNetworkAvailable -MultipleInstances IgnoreNew -StartWhenAvailable -Compatibility win8  -ExecutionTimeLimit 0   -DisallowHardTerminate       
        # 新任务   最后是任务描述
        $D = New-ScheduledTask -Action $A -Principal $P -Trigger $T -Settings $S  -Description "每日自动更新必应桌面壁纸"
        # 注册任务     
        Register-ScheduledTask -TaskName "每日自动更换bing壁纸" -InputObject $D
    }
    return
}

[uri]$binguri="https://cn.bing.com/HPImageArchive.aspx?format=js&n=1&pid=hp"
$T="{0:yyyy.MM.dd`tHH:mm′ss″}" -f (Get-Date)
function out ([string]$p)
{
    Out-File -FilePath $PSScriptRoot\BingWallpaper.log -InputObject "$T`t$p" -Append
}

class bing:Hashtable{
    
    [uri]$Uri
    hidden[uri]$DownUri
    [string]$Copyright
    hidden[string]$DownFile

    bing ([string]$uri){
        [uri]$this.uri=$uri
    }
    
    bingImDo (){
        $d=try{
            Invoke-RestMethod @this
        }catch{
            $_.Exception.Response
        }

        if ($d.images)
        {
            $this.DownUri="https://cn.bing.com"+$d.images.url
            $this.Copyright=$d.images.copyright.Replace(" (","`n(")
            $this.DownFile=$PSScriptRoot+"/"+$d.images.enddate+".jpg"
            $client = new-object System.Net.WebClient
            $client.DownloadFile( $this.DownUri ,$this.DownFile)
        }else{
            out "错误码: $($d.StatusCode)($($d.StatusCode.value__))"
        }
    }
}

Add-Type -AssemblyName System.Drawing
function Draw-WatemarkString()
{
    param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [ValidatePattern("(.jpg)|(.png)|(.gif)$")]
        [io.fileinfo]$ImageFile,
 
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$Text,
 
        [ValidateSet("NorthWest", "NorthEast", "SouthWest","SouthEast")]
        [string]$Location='SouthEast',
 
        [System.Drawing.Color]$Color= [System.Drawing.Color]::AntiqueWhite,
 
        [ValidateRange(1,[system.single]::MaxValue)]
        [float]$FontSize = 15,
 
        [string]$FontFamily='Microsoft YaHei',
 
        [ValidateRange(0,[system.single]::MaxValue)]
        [int]$margin = 45,
 
        [switch]$Bold,
        [Switch]$Italic,
        [switch]$Underline,
        [switch]$Strikeout
    )
 
    # test image file exists
    if( -not (Test-Path $ImageFile) )
    {
        throw "图片文件${ImageFile}不存在. "
    }
 
    # font style
    [drawing.fontstyle]$fontStyle= [drawing.fontstyle]::Regular
    (
        ($Bold,[drawing.fontstyle]::Bold),
        ($Italic,[drawing.fontstyle]::Italic),
        ($Underline,[drawing.fontstyle]::Underline),
        ($Strikeout,[drawing.fontstyle]::Strikeout)
    ) | foreach {
        if($_[0])
        {
            $fontStyle = $fontStyle -bxor $_[1]
        }
    }
 
    # graphics and brush
    $font = New-Object System.Drawing.Font($FontFamily, $FontSize,$fontStyle)
    $img = [drawing.image]::FromFile($ImageFile)
    $drawBrush =  [drawing.solidbrush]$Color
    $g = [drawing.graphics]::FromImage($img)
    $textSize = $g.MeasureString($Text,$font).ToPointF()
    $pointF = New-Object System.Drawing.PointF
 <#
    # location
    switch ($Location)
    {
        'NorthWest'
        {
            $pointF.X = $margin
            $pointF.Y = $margin
        }
 
        'NorthEast'
        {
            $pointF.X = $img.Width - $margin - $textSize.X
            $pointF.Y = $margin
        }
 
        'SouthWest'
        {
            $pointF.X = $margin
            $pointF.Y = $img.Height - $margin - $textSize.Y
        }
 
        'SouthEast'
        {#>
            $pointF.X = $img.Width - $margin - $textSize.X
            $pointF.Y = $img.Height - $margin - $textSize.Y
      <#  }
    }#>
 
    # draw string and save image to temporary file
    $g.DrawString($Text,$font,$drawBrush,$pointF)
    $tempImage = '{0}.jpg' -f $ImageFile
    $img.Save($tempImage)
 
    # dispose graphics, brush, image
    $g.Dispose()
    $drawBrush.Dispose()
    $img.Dispose()
 
    # copy temporary file to original source
    Copy-Item $tempImage $ImageFile -Force
    Remove-Item $tempImage
 
}

#完全看不懂,天书
# 注册定义的类
Add-Type @" 
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Wallpaper
{
	public enum Style : int
	{
		Center, Stretch
	}
	public class Setter {
		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 lpvParam, int fuWinIni);
			
		public static void SetWallpaper ( string path) {
			SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange );
			RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);

				key.SetValue(@"WallpaperStyle", "10") ;
				key.SetValue(@"TileWallpaper", "0") ;

			key.Close();
		}
	}
}
"@



$bin=[bing]::new($binguri)
echo 获取图片
$bin.bingImDo()
if ($bin.Count -lt 4)
{
    Write-Warning "获取失败"
    return
}
$g=$T,$bin.Copyright -join "`n"
Draw-WatemarkString -ImageFile $bin.DownFile -Text $g

echo 应用新壁纸
[Wallpaper.Setter]::SetWallpaper( $bin.DownFile )
Remove-Item $bin.DownFile #删除壁纸文件
echo 完成!
Start-Sleep -Seconds 3
#exit
  • 必应
    4 引用 • 15 回帖
  • 壁纸
    11 引用 • 62 回帖
  • 工具

    子曰:“工欲善其事,必先利其器。”

    176 引用 • 497 回帖 • 3 关注

赞助商 我要投放

回帖
请输入回帖内容 ...