Demo-IntuneLocalAdmin.ps1


<#PSScriptInfo
 
.VERSION 1.0.0.0
 
.GUID d106892e-9c13-4de4-a0a5-23420e40b399
 
.AUTHOR Frits van Drie
 
.COMPANYNAME 3-Link Opleidingen (3-link.nl)
 
.COPYRIGHT (c) 2023 3-Link bv (NL). Anyone is free to use and distribute this module freely without modification. If you like this or experience failures, please notify me
 
.TAGS Demoscript
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES microsoft.graph.authentication
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES 1.0.0.0 (2024-09-17) Initial release
 
.PRIVATEDATA
 
#>



<#
    .SYNOPSIS
        Some Intune Device Configuration policies for demo
 
    .DESCRIPTION
        This script can be used to demonstrate various device configuration policies in Intune in a demo environment.
 
    .NOTES
        Author : Frits van Drie (f.vandrie)
        Company : 3-Link Opleidingen (3-Link.nl)
 
        This script is developed for training and demonstration only. Do not run this script in a production environment.
 
        A perfect way to run this script is to open it in your favorite PowerShell editor and run each region separate in sequence.
 
#>
                   



#region: Functions

    Function Get-3gIntuneDeviceConfigurationProfile {

        <#
            .NOTES
             
                Name: Get-3gIntuneDeviceConfigurationProfile
                Author: Frits van Drie (3-Link.nl)
                Date: 2024-06-18
     
        #>


        [CmdletBinding()]

        param()

        $batch = @'
{
    "requests":[
        {
            "id":"/deviceManagement/configurationPolicies",
            "method":"GET",
            "url":"/deviceManagement/configurationPolicies?$top=1000&$select=id,name,lastModifiedDateTime,roleScopeTagIds,createdDateTime&$orderBy=name asc"
        },
        {
            "id":"/deviceManagement/deviceConfigurations",
            "method":"GET",
            "url":"/deviceManagement/deviceConfigurations?$top=1000&$select=id,displayName,lastModifiedDateTime,roleScopeTagIds,createdDateTime&$orderBy=displayName asc"
        },
        {
            "id":"/deviceManagement/groupPolicyConfigurations",
            "method":"GET",
            "url":"/deviceManagement/groupPolicyConfigurations?$top=1500"
        },
        {
            "id":"/deviceAppManagement/mobileAppConfigurations",
            "method":"GET",
            "url":"/deviceAppManagement/mobileAppConfigurations?$top=1000&$filter=microsoft.graph.androidManagedStoreAppConfiguration/appSupportsOemConfig eq true"
        },
        {
            "id":"/deviceManagement/resourceAccessProfiles",
            "method":"GET",
            "url":"/deviceManagement/resourceAccessProfiles?$top=1000"
        }
    ]
}
'@

        #$batch | ConvertFrom-Json
        $uri = 'https://graph.microsoft.com/beta/$batch'
        Write-Verbose "Invoke-MgGraphRequest"
        Write-Verbose "`tUri : '$uri'"
        Write-Verbose "`tMethod: POST"
        $restResult = (Invoke-MgGraphRequest -Method POST -Uri $uri -Body $batch -OutputType PSObject -ErrorAction Stop) #.value


        foreach ($response in $restResult.responses) {

            foreach ($item in $response.body.value) {
                $ht = @{
                    '@odata.type'        = $item.'@odata.type'
                    id                   = $item.id
                    createdDateTime      = $item.createdDateTime
                    lastModifiedDateTime = $item.lastModifiedDateTime
                    roleScopeTagIds      = $item.roleScopeTagIds
                    resourceType         = $response.id
                }
                if ($item.displayName) {
                    $ht.Add('displayName', $item.displayName)
                }
                elseif ($item.profileName) {
                    $ht.Add('displayName', $item.profileName)
                }
                elseif ($item.name) {
                    $ht.Add('displayName', $item.name)
                }
                else {
                    $ht.Add('displayName', '')
                }

                $objOut = [PSCustomObject]$ht
                Write-Verbose ("Output: {0} [{1}] " -f ($objOut.displayName).PadRight(60), $objOut.id)
                Write-Output $objOut
            }

        }

    }
    Function Remove-3gIntuneDeviceConfigurationProfile {

        [CmdletBinding()]

        param(
        
            [Parameter(mandatory=$true)]
            [String[]]$Id,

            [Parameter(mandatory=$true)]
            [ValidateSet(
                '/deviceManagement/configurationPolicies',
                '/deviceManagement/deviceConfigurationProfiles',
                '/deviceManagement/deviceConfigurations',
                '/deviceManagement/groupPolicyConfigurations',
                '/deviceAppManagement/mobileAppConfigurations',
                '/deviceAppManagement/mobileAppConfigurations')
            ]
            [String[]]$ResourceType,

            [string]$ApiVersion = 'beta'

        )


        $uri = "https://graph.microsoft.com/$ApiVersion$ResourceType/$Id"
        Write-Verbose "Invoke-MgGraphRequest"
        Write-Verbose "`tUri : '$uri'"
        Write-Verbose "`tMethod: DELETE"
        try {
            $restResult = (Invoke-MgGraphRequest -Method DELETE -Uri $uri -OutputType PSObject -ErrorAction Stop) #.value
            Write-Verbose 'Success'
        }
        catch {
            Write-Verbose 'Failed'
            throw $_
        }


        Write-Output $restResult

    }
    Function NewMgDeviceManagementDeviceConfigurationAssignment {

        [CmdletBinding()]

        param (
            [parameter(Mandatory=$true)]
            $deviceConfigurationId,

            [parameter(Mandatory=$true)]
            $target
            
        )

        Write-Host "Assigning group: 'All Devices'`t" -NoNewline
        try {
            $assignments = New-MgBetaDeviceManagementDeviceConfigurationAssignment -DeviceConfigurationId $deviceConfigurationId -Target $target -ErrorAction Stop
            #$assignments = New-MgBetaDeviceManagementConfigurationPolicyAssignment -DeviceManagementConfigurationPolicyId $deviceConfigurationId -Target $target -ErrorAction Stop
            Write-Host "Success" -f Green
        }
        catch {
            Write-Host "Red" -f Red
        }

        Write-Host "Current Assignments:"
        $assignments = Get-MgBetaDeviceManagementDeviceConfigurationAssignment -DeviceConfigurationId $deviceConfigurationId
        #$assignments = Get-MgBetaDeviceManagementConfigurationPolicyAssignment -DeviceManagementConfigurationPolicyId $deviceConfigurationId

        foreach ($item in $assignments.target.additionalProperties) {
            $odataType = $item.'@odata.type'
            if ($odataType -like '*exclusion*') {
                Write-Host "`tExcluded: " -f Yellow -NoNewline
            }
            else {
                Write-Host "`tIncluded: " -f Green -NoNewline
            }

            if ($item.groupId) {
                $grpDisplayName = (Get-MgGroup -GroupId $item.groupId).DisplayName
                Write-Host $grpDisplayName "[$($item.groupId)]"
            }
            else {
                Write-Host $item.'@odata.type'
            }

        }

    }

#endregion

#region: modules

    $reqModules = 'microsoft.graph', 'microsoft.graph.beta'

    foreach ($name in $reqModules) {
        try {
            Write-Host "Install module: $name"
            if (Get-Module $name -ListAvailable) {
                Write-Host "Present" -ForegroundColor Yellow
                continue
            }
            Install-Module -Name $name -Repository PSGallery -ErrorAction Stop
            Write-Host "Success" -ForegroundColor Green
        }
        catch {
            Write-Host "Failed" -ForegroundColor Red
            throw $_
        }
    }

#endregion

#region: Connections

    $scopes = @(
        'DeviceManagementConfiguration.ReadWrite.All',
        'DeviceManagementApps.ReadWrite.All'
    )
    try {
        Write-Host "Connecting to Graph`t" -NoNewline
        Connect-MgGraph -Scopes $scopes -NoWelcome -ErrorAction Stop
        Write-Host "Connected" -f Green
    }
    catch {
        Write-Host "Failed" -f Red
        Write-Error $_
    }

#endregion

break

#region: Create local Administrator account

  # PowerShell script: https://www.prajwaldesai.com/create-a-local-admin-account-using-intune/

    $policyName = 'Create local Administrator account'
    Write-Host "Device Configuration Policy name: $policyName"

    $scopes   = @(
        'DeviceManagementConfiguration.ReadWrite.All',
        'DeviceManagementApps.ReadWrite.All',
        'Group.Read.All'
    )
    Connect-MgGraph -NoWelcome -Scopes $scopes
    
    Write-Host "Get existing Policy"
    # $deviceConfigurations = Get-MgDeviceManagementDeviceConfiguration | Where DisplayName -eq $policyName # Not retrieving all kinds of policies
    $deviceConfigurations = Get-3gIntuneDeviceConfigurationProfile | Where DisplayName -eq $policyName
    Write-Host "Found: $(($deviceConfigurations|Measure-Object).count)" -f Green

    foreach ($config in $deviceConfigurations) {
        try {
            Write-Host "Removing existing Policy: $($config.id)`t" -NoNewline
            # Remove-MgDeviceManagementDeviceConfiguration -DeviceConfigurationId $config.Id -ErrorAction Stop
            $removed = Remove-3gIntuneDeviceConfigurationProfile -Id $config.Id -ResourceType $config.resourceType -ErrorAction Stop

            Write-Host "Success" -f Green
        }
        catch {
            Write-Host "Failed" -f Red
            throw $_
        }
    }


    $jsonBody = @"
{
    "@odata.type" : "#microsoft.graph.windows10CustomConfiguration",
    "displayName" : "$policyName",
    "omaSettings" : [
        {
            "@odata.type" : '#microsoft.graph.omaSettingString',
            "displayName" : 'AddUser-SetPassword',
            "omaUri" : "./Device/Vendor/MSFT/Accounts/Users/Japie/Password",
            "value" : 'Pa55w.rd'
        },
        {
            "@odata.type" : '#microsoft.graph.omaSettingInteger',
            "displayName" : 'AddToLocalAdministratorsGroup',
            "omaUri" : "./Device/Vendor/MSFT/Accounts/Users/Japie/LocalUserGroup",
            "value" : 2
        }
    ]
}
"@

    $test     = $jsonBody | ConvertFrom-Json -ErrorAction Stop

    Write-Host "Creating new Policy`t" -NoNewline
    try {
        #New-MgDeviceManagementDeviceConfiguration -DisplayName $policyDisplayName -AdditionalProperties $jsonBody
        $method  = 'POST'
        $version = 'beta'
        $uri     = "https://graph.microsoft.com/$version/deviceManagement/deviceConfigurations"
        $restResult = (Invoke-MgGraphRequest -Method $method -Uri $uri -Body $jsonBody -ErrorAction Stop).value
        Write-Host "Success" -f Green
    }
    catch {
        Write-Host "Failed" -f Red
        throw $_
    }


    # Assign policy to 'All Devices'
    $deviceConfigurations = Get-3gIntuneDeviceConfigurationProfile | Where DisplayName -eq $policyName

    Write-Host "Assigning 'All Devices' to policy: $($deviceConfigurations.id)"
    $target = @{'@odata.type' ='#microsoft.graph.allDevicesAssignmentTarget'}
    NewMgDeviceManagementDeviceConfigurationAssignment -DeviceConfigurationId $deviceConfigurations.Id -Target $target -ErrorAction Stop

#endregion

#region: Enable built-in Administrator account


    # start 'https://www.prajwaldesai.com/enable-disable-built-in-administrator-account-using-intune/'

    $policyName = 'Enable built-in local Administrator account'
    Write-Host "Device Configuration Policy name: $policyName"

    $scopes   = @(
        'DeviceManagementConfiguration.ReadWrite.All',
        'DeviceManagementApps.ReadWrite.All'
    )
    Connect-MgGraph -NoWelcome -Scopes $scopes
    Write-Host "Get existing Policy"
    #$deviceConfigurations = Get-MgDeviceManagementDeviceConfiguration | Where DisplayName -eq $policyName # Not retrieving all
    $deviceConfigurations = Get-3gIntuneDeviceConfigurationProfile | Where DisplayName -eq $policyName
    Write-Host "Found: $(($deviceConfigurations|Measure-Object).count)" -f Green

    foreach ($config in $deviceConfigurations) {
        try {
            Write-Host "Removing existing Policy: $($config.id)`t" -NoNewline
            # Remove-MgDeviceManagementDeviceConfiguration -DeviceConfigurationId $config.Id -ErrorAction Stop
            $removed = Remove-3gIntuneDeviceConfigurationProfile -Id $config.Id -ResourceType $config.resourceType -ErrorAction Stop

            Write-Host "Success" -f Green
        }
        catch {
            Write-Host "Failed" -f Red
            throw $_
        }
    }

    $jsonBody = @"
{
    "@odata.type" : "#microsoft.graph.windows10CustomConfiguration",
    "displayName" : "$policyName",
    "omaSettings" : [
        {
            "@odata.type" : '#microsoft.graph.omaSettingInteger',
            "displayName" : 'EnableBuiltInLocalAdmin',
            "omaUri" : './Device/Vendor/MSFT/Policy/Config/LocalPoliciesSecurityOptions/Accounts_EnableAdministratorAccountStatus',
            "value" : 1
        }
    ]
}
"@

    $test     = $jsonBody | ConvertFrom-Json -ErrorAction Stop

    Write-Host "Creating new Policy`t" -NoNewline
    try {
        #New-MgDeviceManagementDeviceConfiguration -DisplayName $policyDisplayName -AdditionalProperties $jsonBody
        $method  = 'POST'
        $version = 'beta'
        $uri     = "https://graph.microsoft.com/$version/deviceManagement/deviceConfigurations"
        $restResult = (Invoke-MgGraphRequest -Method $method -Uri $uri -Body $jsonBody -ErrorAction Stop).value
        Write-Host "Success" -f Green
    }
    catch {
        Write-Host "Failed" -f Red
        throw $_
    }


    # Assign policy to 'All Devices'
    $deviceConfigurations = Get-3gIntuneDeviceConfigurationProfile | Where DisplayName -eq $policyName
    Write-Host "Found: $(($deviceConfigurations|Measure-Object).count)" -f Green

    # $allUsersId = 'acacacac-9df4-4c7d-9d50-4ef0226f57a9'
    # $allDevicesId = 'adadadad-808e-44e2-905a-0b7873a8a531'

    $target = @{'@odata.type' ='#microsoft.graph.allDevicesAssignmentTarget'}
    NewMgDeviceManagementDeviceConfigurationAssignment -DeviceConfigurationId $deviceConfigurations.Id -Target $target

#endregion

#region: Rename built-in Administrator account

    # start https://www.prajwaldesai.com/rename-built-in-administrator-account-intune/
    $policyName = 'Rename local built-in Administrator'

    Write-Host "Device Configuration Policy name: $policyName"

    $scopes   = @(
        'DeviceManagementConfiguration.ReadWrite.All',
        'DeviceManagementApps.ReadWrite.All'
    )
    Connect-MgGraph -NoWelcome -Scopes $scopes

    # Get existing policies
    Write-Host "Get existing Policy"
    #$deviceConfigurations = Get-MgBetaDeviceManagementDeviceConfigurationProfile | Where DisplayName -eq $policyName # Not retrieving all

    $deviceConfigurations = Get-3gIntuneDeviceConfigurationProfile | Where DisplayName -eq $policyName
    Write-Host "Found: $(($deviceConfigurations|Measure-Object).count)" -f Green

    # Remove existing policies
    foreach ($config in $deviceConfigurations) {
        try {
            Write-Host "Removing existing Policy: $($config.id)`t" -NoNewline
            # Remove-MgDeviceManagementDeviceConfiguration -DeviceConfigurationId $config.Id -ErrorAction Stop
            $removed = Remove-3gIntuneDeviceConfigurationProfile -Id $config.Id -ResourceType "/deviceManagement/configurationPolicies" -ErrorAction Stop

            Write-Host "Success" -f Green
        }
        catch {
            Write-Host "Failed" -f Red
            throw $_
        }
    }

    # Create new Policy
    $newAdminName = 'LocalRoot'
    $uri = "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies"
    $jsonBody = @"
{
    'name': '$policyName',
    'description' : '',
    'platforms' : 'windows10',
    'technologies':'mdm',
    'roleScopeTagIds':['0'],
    'settings':[
        {
            '@odata.type':'#microsoft.graph.deviceManagementConfigurationSetting',
            'settingInstance':
                {
                    '@odata.type':'#microsoft.graph.deviceManagementConfigurationSimpleSettingInstance',
                    'settingDefinitionId':'device_vendor_msft_policy_config_localpoliciessecurityoptions_accounts_renameadministratoraccount','simpleSettingValue':{'@odata.type':'#microsoft.graph.deviceManagementConfigurationStringSettingValue',
                    'value':'$newAdminName'
                }
            }
        }
    ]
}
"@


    try {
        Write-Host "Creating new policy`t" -NoNewline
        $restResult = Invoke-MgGraphRequest -Method POST -Uri $uri -Body $jsonBody -ErrorAction Stop
        Write-Host "Success" -f Green
    }
    catch {
        Write-Host "Failed" -f Red
        throw $_
    }


    # Assign policy to 'All Devices'
    $deviceConfigurations = Get-3gIntuneDeviceConfigurationProfile | Where DisplayName -eq $policyName

    Write-Host "Assigning 'All Devices' to policy: $($deviceConfigurations.id) `t" -NoNewline
    #Set-MgBetaDeviceManagementConfigurationPolicy -DeviceManagementConfigurationPolicyId $deviceConfigurationId -BodyParameter $params

    $jsonBody = @"
{
    "assignments": [
        {
            "target": {
                "@odata.type": "#microsoft.graph.allDevicesAssignmentTarget"
            }
        }
    ]
}
"@


    try {
        $uri = "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies/$($deviceConfigurations.Id)/assign"
        $restResult = Invoke-MgGraphRequest -Method POST -Uri $uri -Body $jsonBody -ErrorAction Stop
        Write-Host "Success" -f Green
    }
    catch {
        Write-Host "Failed" -f Red
        throw $_

    }

#endregion