Functions/New-IntuneScopeTag.ps1

function New-IntuneScopeTag {
    <#
    .SYNOPSIS
        Creates a new scope tag in Intune.
 
    .DESCRIPTION
        Calls the Graph API endpoint to create a new scope tag with the given display name and description.
 
    .PARAMETER TagName
        The display name for the scope tag.
 
    .PARAMETER Description
        (Optional) A description for the scope tag.
 
    .EXAMPLE
        New-IntuneScopeTag -TagName "Finance" -Description "Scope tag for Finance devices"
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$ScopeTagName,

        [Parameter(Mandatory = $true)]
        [string]$Description,

        [Parameter(Mandatory = $false)]
        [string]$DeviceGroupName

    )

    # Check if connected to Microsoft Graph
    if (-not (Get-MgContext -ErrorAction SilentlyContinue)) {
        Write-Error "You must run Connect-IntuneGraph before calling this function."
        return
    }

    # Create Scope Tags
    # Check to see if scope tag exists
    If (!(Get-MgBetaDeviceManagementRoleScopeTag -Filter "displayName eq '$ScopeTagName'")) {
        $groupDeviceGroupId = $((Get-MgBetaGroup -Filter "DisplayName eq '$DeviceGroupName'").Id)
        $ScopeTagParams = @{
            displayName = $ScopeTagName
            description = $Description
            assignments = @(
                @{
                    target = @{
                        "@odata.type" = "#microsoft.graph.groupAssignmentTarget"
                        groupId       = "$groupDeviceGroupId"
                    }
                }
            )

        }
        New-MgBetaDeviceManagementRoleScopeTag -BodyParameter $ScopeTagParams
        Write-Host "Creating new scope tag: $ScopeTagName" -ForegroundColor Cyan
    }
    Else {
        # Update newly created Scope Tag or existing
        $groupDeviceGroupId = $((Get-MgBetaGroup -Filter "DisplayName eq '$DeviceGroupName'").Id)
        $ScopeTagParams = @{
            assignments = @(
                @{
                    target = @{
                        "@odata.type" = "#microsoft.graph.groupAssignmentTarget"
                        groupId       = "$groupDeviceGroupId"
                    }
                }
            )
        }
        $roleScopeTagId = $((Get-MgBetaDeviceManagementRoleScopeTag -Filter "DisplayName eq '$ScopeTagName'").Id)
        Set-MgBetaDeviceManagementRoleScopeTag -RoleScopeTagId $roleScopeTagId -BodyParameter $ScopeTagParams
        Write-Host "Updating scope tag: $ScopeTagName" -ForegroundColor Cyan
    }
}