impact/Set-ImpactWallpaper.ps1

function Set-ImpactWallpaper {
[CmdletBinding()]  # Add cmdlet features.
    Param (
        # Define parameters below, each separated by a comma

        [Parameter(Mandatory=$False)]
        [ValidatePattern("^.*\.(png|PNG)$")]
        [string]$DesktopWallpaperPath,

        [Parameter(Mandatory=$False)]
        [ValidatePattern("^.*\.(png|PNG)$")]
        [string]$LockscreenWallpaperPath,

        [Parameter(Mandatory=$False)]
        [string] $AzureUPN
    )

Function Get-DeviceConfigurationPolicy(){

<#
.SYNOPSIS
This function is used to get device configuration policies from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets any device configuration policies
.EXAMPLE
Get-DeviceConfigurationPolicy
Returns any device configuration policies configured in Intune
.NOTES
NAME: Get-DeviceConfigurationPolicy
#>


[cmdletbinding()]

param
(
    $name
)

$graphApiVersion = "Beta"
$DCP_resource = "deviceManagement/deviceConfigurations"

    try {

        if($Name){

        $uri = "https://graph.microsoft.com/$graphApiVersion/$($DCP_resource)"
        (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value | Where-Object { ($_.'displayName').contains("$Name") }

        }

        else {

        $uri = "https://graph.microsoft.com/$graphApiVersion/$($DCP_resource)"
        (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value

        }

    }

    catch {

    $ex = $_.Exception
    $errorResponse = $ex.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($errorResponse)
    $reader.BaseStream.Position = 0
    $reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd();
    Write-Host "Response content:`n$responseBody" -f Red
    Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
    write-host
    break

    }

}
Function Get-DeviceConfigurationPolicyAssignment(){

<#
.SYNOPSIS
This function is used to get device configuration policy assignment from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets a device configuration policy assignment
.EXAMPLE
Get-DeviceConfigurationPolicyAssignment $id guid
Returns any device configuration policy assignment configured in Intune
.NOTES
NAME: Get-DeviceConfigurationPolicyAssignment
#>


[cmdletbinding()]

param
(
    [Parameter(Mandatory=$true,HelpMessage="Enter id (guid) for the Device Configuration Policy you want to check assignment")]
    $id
)

$graphApiVersion = "Beta"
$DCP_resource = "deviceManagement/deviceConfigurations"

    try {

    $uri = "https://graph.microsoft.com/$graphApiVersion/$($DCP_resource)/$id/groupAssignments"
    (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value

    }

    catch {

    $ex = $_.Exception
    $errorResponse = $ex.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($errorResponse)
    $reader.BaseStream.Position = 0
    $reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd();
    Write-Host "Response content:`n$responseBody" -f Red
    Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
    write-host
    break

    }

}
Function Get-AADGroup(){

<#
.SYNOPSIS
This function is used to get AAD Groups from the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and gets any Groups registered with AAD
.EXAMPLE
Get-AADGroup
Returns all users registered with Azure AD
.NOTES
NAME: Get-AADGroup
#>


[cmdletbinding()]

param
(
    $GroupName,
    $id,
    [switch]$Members
)

# Defining Variables
$graphApiVersion = "v1.0"
$Group_resource = "groups"
# pseudo-group identifiers for all users and all devices
[string]$AllUsers   = "acacacac-9df4-4c7d-9d50-4ef0226f57a9"
[string]$AllDevices = "adadadad-808e-44e2-905a-0b7873a8a531"

    try {

        if($id){

        $uri = "https://graph.microsoft.com/$graphApiVersion/$($Group_resource)?`$filter=id eq '$id'"
        switch ( $id ) {
                $AllUsers   { $grp = [PSCustomObject]@{ displayName = "All users"}; $grp           }
                $AllDevices { $grp = [PSCustomObject]@{ displayName = "All devices"}; $grp         }
                default     { (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value  }
                }
                
        }

        elseif($GroupName -eq "" -or $GroupName -eq $null){

        $uri = "https://graph.microsoft.com/$graphApiVersion/$($Group_resource)"
        (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value

        }

        else {

            if(!$Members){

            $uri = "https://graph.microsoft.com/$graphApiVersion/$($Group_resource)?`$filter=displayname eq '$GroupName'"
            (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value

            }

            elseif($Members){

            $uri = "https://graph.microsoft.com/$graphApiVersion/$($Group_resource)?`$filter=displayname eq '$GroupName'"
            $Group = (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value

                if($Group){

                $GID = $Group.id

                $Group.displayName
                write-host

                $uri = "https://graph.microsoft.com/$graphApiVersion/$($Group_resource)/$GID/Members"
                (Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get).Value

                }

            }

        }

    }

    catch {

    $ex = $_.Exception
    $errorResponse = $ex.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($errorResponse)
    $reader.BaseStream.Position = 0
    $reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd();
    Write-Host "Response content:`n$responseBody" -f Red
    Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
    write-host
    break

    }

}
Function Set-DeviceConfigurationPolicy(){

<#
.SYNOPSIS
This function is used to add an device configuration policy using the Graph API REST interface
.DESCRIPTION
The function connects to the Graph API Interface and adds a device configuration policy
.EXAMPLE
Add-DeviceConfigurationPolicy -JSON $JSON
Adds a device configuration policy in Intune
.NOTES
NAME: Add-DeviceConfigurationPolicy
#>


[cmdletbinding()]

param
(
    $JSON,
    $TargetPolicyID
)

$graphApiVersion = "Beta"
$DCP_resource = "deviceManagement/deviceConfigurations"
Write-Verbose "Resource: $DCP_resource"

    try {

        if($JSON -eq "" -or $JSON -eq $null){

        write-host "No JSON specified, please specify valid JSON target policy..." -f Red

        }

        else {

        Test-JSON -JSON $JSON

        $uri = "https://graph.microsoft.com/$graphApiVersion/$($DCP_resource)/$TargetPolicyID"
        Invoke-RestMethod -Uri $uri -Headers $authToken -Method Patch -Body $JSON -ContentType "application/json"

        }

    }

    catch {

    $ex = $_.Exception
    $errorResponse = $ex.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($errorResponse)
    $reader.BaseStream.Position = 0
    $reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd();
    Write-Host "Response content:`n$responseBody" -f Red
    Write-Error "Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)"
    write-host
    break

    }

}
Function Test-JSON(){

<#
.SYNOPSIS
This function is used to test if the JSON passed to a REST Post request is valid
.DESCRIPTION
The function tests if the JSON passed to the REST Post is valid
.EXAMPLE
Test-JSON -JSON $JSON
Test if the JSON is valid before calling the Graph REST interface
.NOTES
NAME: Test-AuthHeader
#>


param (

$JSON

)

    try {

    $TestJSON = ConvertFrom-Json $JSON -ErrorAction Stop
    $validJson = $true

    }

    catch {

    $validJson = $false
    $_.Exception

    }

    if (!$validJson){

    Write-Host "Provided JSON isn't in valid JSON format" -f Red
    break

    }

}
If (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
If ({Get-Module AzureRM -ListAvailable} -eq $null) {
    Write-Error "AzureRM Module not installed."
    break
    } else {
    Write-Host "Importing AzureRM"
    Import-Module AzureRM
    }
#region Authentication

write-host

if($AzureUPN -eq $null -or $AzureUPN -eq ""){

    $User = whoami /upn

    } else {
    $User = $AzureUPN
    }

# Getting the authorization token
$global:authToken = Get-AuthToken -User $User -clientID "d1ddf0e4-d672-4dae-b554-9d5bdfd93547" -UIMode Auto



#endregion



#Write-Host Connecting to Azure...
If (Get-AzureRMContext -eq $null) {Connect-AzureRMAccount -Tenant 7035fda4-ac16-4ee3-ba72-1d2caeb6d457}

Write-Host Connecting to Azure Storage...
$ImpactStorageAccount = Get-AzureRmStorageAccount -Name "impactpartnership" -ResourceGroupName "Impact-Partnership.Infrastructure"

If (($DesktopWallpaperPath -eq "") -and ($LockscreenWallpaperPath -eq "") ) {
    Write-error "No wallpapers definied."
    } else {
    If (Test-Path "$DesktopWallpaperPath" -ErrorAction SilentlyContinue) {
        Write-Host Uploading new Desktop Wallpaper...
        Set-AzureStorageBlobContent -File $DesktopWallpaperPath -Container public-resources -Context $ImpactStorageAccount.Context -Blob "Wallpaper.png" -Force -Confirm:$False}
    If (Test-Path "$LockscreenWallpaperPath" -ErrorAction SilentlyContinue) {
        Write-Host Uploading new Lockscreen Wallpaper...
        Set-AzureStorageBlobContent -File $LockscreenWallpaperPath -Container public-resources -Context $ImpactStorageAccount.Context -Blob "Lockscreen.png" -Force -Confirm:$False}

    Write-Host Refreshing Intune Policy...
    $CurrentWallpaperPolicy = Get-DeviceConfigurationPolicy -Name "W10 - Wallpaper"
    Write-Host "Current Desktop String: " $CurrentWallpaperPolicy.personalizationDesktopImageUrl
    Write-Host "Current Lockscreen String: " $CurrentWallpaperPolicy.personalizationLockScreenImageUrl
    
    If ($CurrentWallpaperPolicy.personalizationDesktopImageUrl -eq "https://impactpartnership.blob.core.windows.net/public-resources/Wallpaper.png") {
        $CurrentWallpaperPolicy.personalizationDesktopImageUrl = "https://impactpartnership.blob.core.windows.net/public-resources/Wallpaper.png?"
        } else {
        $CurrentWallpaperPolicy.personalizationDesktopImageUrl = "https://impactpartnership.blob.core.windows.net/public-resources/Wallpaper.png"}
    
    If ($CurrentWallpaperPolicy.personalizationLockscreenImageUrl -eq "https://impactpartnership.blob.core.windows.net/public-resources/Lockscreen.png") {
        $CurrentWallpaperPolicy.personalizationLockscreenImageUrl = "https://impactpartnership.blob.core.windows.net/public-resources/Lockscreen.png?"
        } else { 
        $CurrentWallpaperPolicy.personalizationLockscreenImageUrl = "https://impactpartnership.blob.core.windows.net/public-resources/Lockscreen.png"}
    
    Write-Host "New Desktop String: " $CurrentWallpaperPolicy.personalizationDesktopImageUrl
    Write-Host "New Lockscreen String: " $CurrentWallpaperPolicy.personalizationLockScreenImageUrl

    $NewPolicyJSON = $CurrentWallpaperPolicy | Select-Object -Property '@odata.type',personalizationDesktopImageURL,personalizationLockScreenImageUrl | ConvertTo-Json
    Test-JSON -JSON $NewPolicyJSON
    Set-DeviceConfigurationPolicy -JSON $NewPolicyJSON -TargetPolicyID $CurrentWallpaperPolicy.id
    }
} else {
Write-Host "This Impact Partnership command requires elevation." -ForegroundColor Red
}
}