Sunday, June 16, 2024
HomePowershellAdd a PowerShell Script to Intune (With PowerShell) From Scratch

Add a PowerShell Script to Intune (With PowerShell) From Scratch


When you’ve got Intune at your group with some PowerShell scripts that you must run on distant machines, this tutorial is for you.

Let’s sort out a undertaking the place we’ll cowl every thing from automating creating an Azure app registration, producing a consumer secret, acquiring a Microsoft Graph API token, and utilizing that token to deploy a tool administration script. It would sound like quite a bit, however belief me, I will information you step-by-step!

Step 1: Set up Required Modules and Authenticate to Azure

First issues first, we have to set up the required PowerShell modules and authenticate to Azure. It is a essential step as a result of with out the fitting modules and correct authentication, nothing else will work. Open up your PowerShell console and run the next instructions:

# Set up obligatory Azure PowerShell modules
Set up-Module 'Az.Sources', 'Az.Accounts'

# Authenticate to Azure
Join-AzAccount

Whenever you run these instructions, you will be prompted to log into your Azure account. Observe the prompts, enter your credentials, and you will be all set.

Step 2: Outline Required Useful resource Entry

Subsequent, we have to outline the useful resource entry that our app registration will want. Particularly, we have to entry the Microsoft Graph API with sure permissions. We’ll outline these permissions in a PowerShell hash desk. This desk consists of the ResourceAppId, which is the ID for Microsoft Graph, and the ResourceAccess, which specifies the permissions our app will want. Right here’s what that appears like:

# Outline required useful resource entry
$requiredResourceAccess = @(
    @{
        ResourceAppId  = "00000003-0000-0000-c000-000000000000"  # Microsoft Graph API ID
        ResourceAccess = @(
            @{
                Id   = "9241abd9-d0e6-425a-bd4f-47ba86e767a4"     # DeviceManagementConfiguration.ReadWrite.All permission ID
                Kind = "Position"
            }
        )
    }
)

Step 3: Create the App Registration

Now that we have outlined the required useful resource entry, let’s create the app registration. This registration primarily tells Azure AD that we wish to create a brand new utility with the desired permissions. Run the next command:

$app = New-AzADApplication -DisplayName DeviceManagementScriptApp -RequiredResourceAccess $requiredResourceAccess

This command will register a brand new utility in Azure AD with the desired permissions. The $app variable now holds the small print of the newly created app.

Step 4: Generate a Shopper Secret

Subsequent, we have to generate a consumer secret for our app registration. Consider this as a password to your app that enables it to authenticate and entry assets securely. This is the way you do it:

$secret = New-AzADAppCredential -ObjectId $app.Id

This command creates a consumer secret, which we’ll use later when making API calls. It is essential to retailer this secret securely as a result of it acts like a password to your app.

Step 5: Receive a Microsoft Graph API Token

Now, we have to create a perform to get a Microsoft Graph API token utilizing our app’s credentials. Tokens are important for proving our identification when calling the API. The perform beneath will assist us acquire this token:

perform getGraphApiToken {
    param (
        [string]$TenantId,
        [string]$ClientId,
        [string]$ClientSecret
    )

    $physique = @{
        grant_type    = "client_credentials"
        scope         = "https://graph.microsoft.com/.default"
        client_id     = $ClientId
        client_secret = $ClientSecret
    }

    $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Methodology Put up -Physique $physique -ContentType "utility/x-www-form-urlencoded"
    $tokenResponse.access_token
}

# Instance utilization
$TenantId = "<Your-Tenant-ID>"
$ClientId = $app.ApplicationId
$ClientSecret = $secret.SecretText
$token = getGraphApiToken -TenantId $TenantId -ClientId $ClientId -ClientSecret $ClientSecret

This perform sends a request to Azure AD’s token endpoint to get an entry token. The Invoke-RestMethod command is vital right here because it handles the HTTP POST request and returns the entry token we want for additional API calls.

Step 6: Put together the Script Content material

Let’s transfer on to making ready the PowerShell script content material we wish to deploy. This script shall be encoded in base64 format as a result of the Graph API expects the script content material on this format. Right here’s the way you do it:

# Outline the script content material
$someScriptContent = @'
## That is some PowerShell script
Check-Path C:
'@

# Encode the script content material to base64
$base64ScriptContent = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($someScriptContent))

We first outline our script content material, then convert it to a base64-encoded string, making certain it’s correctly formatted for transmission through the Graph API.

Step 7: Create the HTTP Physique for the REST Name

Subsequent, let’s put together the HTTP physique for the REST name to the Graph API. This consists of establishing the headers and physique for our request. The headers will include the authorization token, and the physique will embody particulars in regards to the script, reminiscent of its content material and language:

# Put together the headers with the token
$headers = @{
    Authorization  = "Bearer $token"
    'Content material-Kind' = 'utility/json'
}

# Create the HTTP physique for the REST name
$physique = @{
    "@odata.kind"           = "#microsoft.graph.deviceManagementScript"
    "scriptContent"         = $base64ScriptContent
    "scriptLanguage"        = "PowerShell"
    "displayName"           = "Instance Script"
    "description"           = "That is an instance script."
    "runAsUser"             = "system"
    "runAs32Bit"            = $false
    "enforceSignatureCheck" = $false
}

Step 8: Make the API Name

Lastly, let’s arrange the parameters for the REST API name and execute it. This step entails making a POST request to the Graph API endpoint to deploy our machine administration script.

powershellCopy code
# Arrange the params for the REST API name
$irmParams = @ ConvertTo-Json)


# Make the API name
$response = Invoke-RestMethod @irmParams

# Deal with any errors
if ($respStatus -ne 201) {
    throw $response.error.message
} else {
    Write-Output "Script deployed efficiently!"
}

This code block units up the parameters for the Invoke-RestMethod command, which sends our script content material to the desired Graph API endpoint. The StatusCodeVariable captures the response standing code to verify if our request was profitable. If every thing goes properly, you will see “Script deployed efficiently!” printed out.

And there you have got it! You’ve got efficiently automated the method of making an Azure app registration, producing a consumer secret, acquiring a Microsoft Graph API token, and deploying a tool administration script. This highly effective workflow allows you to handle Azure assets effectively and securely. Be happy to customise the script and parameters to fit your particular wants. Pleased scripting!


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments