Entra / Microsoft 365 · Teams
Get Bing images for Teams backgrounds
Fetch daily Bing photos into the Teams background images folder for the last seven days and remove images older than 30 days.
Connect & set up
Run these once per session. All scopes are read-only unless the script makes changes.
# Review required modules and connection steps before running.# Connect to Microsoft Graph or Exchange Online as needed for this script.
Run it
The main script. Copy it, or download the .ps1 and run it from your console.
param([int] $LookbackDays = 30)$TeamsBackgroundFiles = $env:APPDATA + "\Microsoft\Teams\Backgrounds\Uploads\"$Market = "en-US"# Check that the Teams background images folder exists. If not, create itIf (-not (Test-Path -LiteralPath $TeamsBackgroundFiles)) {Try {New-Item -Path $TeamsBackgroundFiles -ItemType Directory -ErrorAction Stop | Out-Null}Catch {Write-Error -Message "Unable to create directory '$TeamsBackgroundFiles'. Error was: $_" -ErrorAction Stop }Write-Host "Folder to store Teams background image files created: '$TeamsBackgroundFiles'" }Else {Write-Host "Folder for Teams background images exists"}# Download the last seven days of Bing imagesCLS ; For ($i=0; $i -le 7; $i++) {$BingUri = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=$i&n=1&mkt=$Market"$BingResponse = Invoke-WebRequest -Method Get -Uri $BingUri$BingContent = ConvertFrom-Json -InputObject $BingResponse.Content # Unpack content$BingBackgroundFile = "https://www.bing.com/"+$BingContent.Images.Url$BingFileName = $BingContent.Images.UrlBase.Split(".")[1]; $BingFileName = $BingFileName.Split("_")[0]+".jpg"$TeamsBackgroundFile = $TeamsBackgroundFiles + "Bing-" + $BingFileNameIf (([System.IO.File]::Exists($TeamsBackgroundFile) -eq $False)) {# File isn't there, so we can downloadTry {Invoke-WebRequest -Method Get -Uri $BingBackgroundFile -OutFile $TeamsBackgroundFileWrite-Host "Downloaded new Bing image" $TeamsBackgroundFile}Catch {Write-Host "Error occurred when downloading image from Bing" }} #End If} #End loop# Clean up Bing images older than 30 days so we keep the number of background images to a reasonable number$RemoveDate = (Get-Date).AddDays(-$LookbackDays)$BingFiles = Get-ChildItem $TeamsBackgroundFiles | Where-Object {($_.LastWriteTime -lt $RemoveDate) -and ($_.Name.Substring(0,5) -eq "Bing-")}If ($BingFiles) {Write-Host "Cleaning up old Bing background images"ForEach ($File in $BingFiles) { Delete-Item $File.FullName -Force}}Write-Host "All done"
Parameters
ParameterDefaultNotes
-LookbackDays30Number of days of Bing images to download for Teams backgrounds.Attribution
Author
Office365itpros