Get-BingImage.psm1
<#
.Synopsis Downloads today's bing wallpaper as your Windows Terminal background image. .Parameter profileIndex Index of profile that you want to set background image to. #> function Get-BingImage { param ([int] $profileIndex = 0) Start-Job -Name GetBingImageForWindowsTerminal -ScriptBlock ${Function:DownloadAndSetBingImage} -ArgumentList $profileIndex | Out-Null <# For Debugging $job = Start-Job... Wait-Job -job $job $result = receive-job -job $job Write-Host $result #> } function DownloadAndSetBingImage { param ([int] $profileIndex) # Windows Terminal data directory $profileDirectory = "$env:LOCALAPPDATA\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState" $bingSaveImage = "$profileDirectory\background.jpg" $bingSaveImageTemp = "$profileDirectory\bing.jpg" $profilePath = "$profileDirectory\profiles.json" # Read Windows Terminal profile $pfile = Get-Content -Raw -Path $profilePath # Remove comments because PS5 doesn't support JSON /w comments # [TODO: PS6 has built-in json with comments support so...] $pfile = $pfile -replace '(?m)(?<=^([^"]|"[^"]*")*)//.*' -replace '(?ms)/\*.*?\*/' $pjson = $pfile | ConvertFrom-Json # If backgroundImage property does not exists then abort if (![bool]$pjson.profiles[$profileIndex].psobject.Properties["backgroundImage"]) { Exit } # Check if we already ran it today if ($pjson.LastRunDate) { if (([DateTime]::Now - [DateTime]$pjson.LastRunDate).TotalDays -lt 1) { Exit } } else { $date = [DateTime]::Now $pjson | Add-Member -MemberType NoteProperty -Name 'LastRunDate' -Value $date } # Send request to Bing # [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $json = Invoke-WebRequest 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-us' | ConvertFrom-Json # Find first image $bingImageUrl = "$("https://www.bing.com")$($json[0].images[0].url)" # Save image to disk Invoke-WebRequest $bingImageUrl -OutFile $bingSaveImageTemp # Set new image location $pjson.profiles[$profileIndex].backgroundImage = $bingSaveImageTemp $pjson.LastRunDate = [DateTime]::Now # Save changes to profile $pjson | ConvertTo-Json | Out-File $profilePath -Encoding UTF8 # Wait for Terminal to refresh Start-Sleep -Seconds 2 # Swap newly downloaded image with the old downloaded one Move-Item -Path $bingSaveImageTemp -Destination $bingSaveImage -Force # Save Changes to profile $pjson.profiles[$profileIndex].backgroundImage = $bingSaveImage $pjson | ConvertTo-Json | Out-File $profilePath -Encoding UTF8 } Export-ModuleMember -Function Get-BingImage |