使用Powershell下载必应搜索壁纸,并且设置为桌面背景  


最近在学习Powershell,为了练手,写了一个必应搜索主页面壁纸下载的脚本,然后设置为桌面背景。

function Resolve-Directory {
    param (
        [Parameter(Mandatory)]
        [string]
        $path
    )

    if (-not (Test-Path -LiteralPath $path)) {
        New-Item -Path $path -ItemType Directory -ErrorAction SilentlyContinue
    }

}

function Get-Image {
    param (
        [Parameter(Mandatory)]
        [string]
        $path,

        [Parameter(Mandatory)]
        [string]
        $url
    )
    #init target directory
    Resolve-Directory -path $path
    $global:web = New-Object System.Net.WebClient
    $response = $web.DownloadString($url)
    $content = ([regex]'<link\s*\w*id=[\"]+(.*?)[\"\s\w]*href=[\"]+(.*?)[\"]+\s*/>').Match($response).Value
    $href = ([regex]'href=[\"]+(.*?)[\"]').Match($content).Value
    $href = $href.Replace('"', "").Replace('href=', "")
    $href
}

function Invoke-MD5 {
    param (
        # Parameter Path
        [Parameter(Mandatory)]
        [string]
        $Path
    )

    begin {
        $global:hashTable = @{ }
    }

    process {
        Get-ChildItem -Path $Path | Where-Object {
            $hash = Get-FileHash -Path $_.FullName -Algorithm MD5
            $hashTable[$hash.Hash] = $hash.Path
        }
    }
    end {

    }
}

function Resolve-WallPaper {
    $dir = "D:\temp\wallpaper"
    $url = "https://cn.bing.com"
    Invoke-MD5 -Path $dir
    $imageUrl = Get-Image -url $url -path $dir
    $fileName = -join ([char[]](65..90 + 97..122) | Get-Random -Count 6) + ".jpg"
    $fullPath = Join-Path -Path $dir $fileName
    $web.DownloadFile(($url + $imageUrl), $fullPath)

    #calculate the md5 value
    $hashValue = (Get-FileHash -Path $fullPath -Algorithm MD5).Hash
    $oldFile = $hashTable[$hashValue]
    if (($oldFile) -and (Test-Path -Path $oldFile)) {
        Remove-Item -Path $fullPath -Force -ErrorAction SilentlyContinue
        $fullPath = $oldFile
    }
    # Setting wallpaper to the regisrty.
    Set-ItemProperty -path 'HKCU:\Control Panel\Desktop\' -name wallpaper -value $fullPath
    # updating the user settings
    rundll32.exe user32.dll, UpdatePerUserSystemParameters
    rundll32.exe user32.dll, UpdatePerUserSystemParameters
    rundll32.exe user32.dll, UpdatePerUserSystemParameters

    explorer.exe $dir
}

下载结果是这样的

×用微信扫描并分享
本文链接: https://www.pstips.net/%e4%bd%bf%e7%94%a8powershell%e4%b8%8b%e8%bd%bd%e5%bf%85%e5%ba%94%e6%90%9c%e7%b4%a2%e5%a3%81%e7%ba%b8.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

发表评论

电子邮件地址不会被公开。 必填项已用*标注