DEV Community

Jaime López
Jaime López

Posted on • Originally published at intranetfromthetrenches.substack.com

Automating SharePoint Embedded: Using PowerShell to Call Graph API Endpoints

Are you tired of the limitations of PowerShell cmdlets when it comes to managing SharePoint Embedded? Don't worry, there's a solution!

By combining the power of Microsoft Graph PowerShell and the SharePoint Embedded Graph API, you can easily automate and streamline your SharePoint Embedded management tasks.

Have you ever wished there were dedicated PowerShell cmdlets for SharePoint Embedded? You're not alone! While PowerShell offers robust tools for regular SharePoint, it currently lacks specific cmdlets for the Embedded environment. This can be a hurdle for administrators who want to leverage the power of scripting for automation.

But there's good news! In previous articles, we explored both the functionalities of SharePoint Embedded Graph API endpoints and the available SharePoint PowerShell commands.

Laptop over a table showing source code by Jantine Doombos in Unsplash

Now, this article will delve into how to leverage Microsoft Graph PowerShell to interact with SharePoint Embedded through the Graph API. We'll bridge the gap and empower you to call those essential Graph API endpoints directly from your PowerShell scripts.

Get ready to simplify your SharePoint Embedded management and boost your productivity. Let's dive in!

What is Microsoft Graph PowerShell

Think of Microsoft Graph PowerShell as a translator. It acts as an API wrapper for the vast capabilities of Microsoft Graph, making those functionalities accessible and usable directly within your familiar PowerShell environment.

The commands are autogenerated directly from the Microsoft Graph API schema. This ensures you always have access to the latest functionalities and updates without needing to wait for individual cmdlet development. Additionally, the cmdlet reference content automatically reflects the API reference, providing clear and up-to-date documentation right at your fingertips.

If you haven't already, here's the official guide to get you started: Microsoft Graph PowerShell Installation Guide.

With Microsoft Graph PowerShell as your ally, you'll be well-equipped to leverage the power of the SharePoint Embedded Graph API and streamline your management experience.

Authenticating with Microsoft Graph

Before we unlock the full potential of calling SharePoint Embedded Graph API endpoints through PowerShell, we need to establish a secure connection. This process is called authentication, and Microsoft Graph PowerShell offers two options: delegated and app-only access.

For this demonstration, we'll focus on app-only access. This method is ideal for scenarios where user interaction isn't required, making it perfect for automating tasks within your scripts.

To establish the connection with Microsoft Graph, we'll utilize the Connect-MgGraph cmdlet. This powerful command streamlines the authentication process, but it requires specific credentials for verification.

To successfully connect, you'll need three key pieces of information:

  1. Client ID: This unique identifier represents your registered application in Entra ID.
  2. Secret Value: This confidential value acts as a password for your application, ensuring secure access.
  3. Tenant ID: This identifies the specific Microsoft 365 tenant where your application resides.

Don't worry, acquiring these credentials is a straightforward process. Simply head over to Entra ID and follow the steps outlined in this helpful guide: Entra ID App Registration Quickstart. Once you've registered your application, you'll be able to retrieve the necessary client ID, secret value, and tenant ID.

Now that you have the credentials, let's leverage the power of PowerShell! Here's the code snippet that demonstrates how to establish a connection using Connect-MgGraph:

<#
.SYNOPSIS
Connects to Microsoft Graph
.DESCRIPTION
Connects to Microsoft Graph using the ClientId and SecretValue
.PARAMETER ClientId
The client id of the application
.PARAMETER SecretValue
The secret value of the application
.PARAMETER TenantId
The tenant id where the application is registered
#>

param(
    [Parameter(Mandatory=$true)]
    [String] $ClientId,

    [Parameter(Mandatory=$true)]
    [String] $SecretValue,

    [Parameter(Mandatory=$true)]
    [String] $TenantId
)

Write-Host "Connecting..." -ForegroundColor Cyan

# Create a secure string from the secret value
$password = ConvertTo-SecureString -String $SecretValue -AsPlainText -Force

# Create a credential object
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ClientId, $password

# Connect to Microsoft Graph
Try {
    Connect-MgGraph -TenantId $TenantId -ClientSecretCredential $credential -ErrorAction Stop
    Write-Host "Connected" -ForegroundColor Green
}
Catch {
    Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
}
Enter fullscreen mode Exit fullscreen mode

Remember to provide your client id, secret and tenant id with your actual credentials. Executing this script initiates the connection with Microsoft Graph, paving the way for you to interact with SharePoint Embedded Graph API endpoints through your PowerShell commands.

Making API Calls Using Microsoft Graph PowerShell

Now that we've established a secure connection with Microsoft Graph, it's time to unleash the true power of this approach – interacting with SharePoint Embedded Graph API endpoints through PowerShell!

Microsoft Graph PowerShell provides a versatile command called Invoke-MgGraphRequest. This powerhouse acts as a universal translator, allowing you to call any Graph API endpoint directly within your PowerShell scripts.

The beauty of Invoke-MgGraphRequest lies in its flexibility. It caters to all aspects of API calls, including method selection, body parameters, and headers.

One of the significant advantages is the seamless handling of authentication. The access token obtained during the connection with Connect-MgGraph is automatically used for subsequent API calls within the same PowerShell session. This eliminates the need to include the token explicitly in each command, streamlining your workflow.

Let's take a practical example to illustrate the power of Invoke-MgGraphRequest. The following code snippet demonstrates how to list the containers of a specific type within SharePoint Embedded:

<#
.SYNOPSIS
Lists the containers for a given container type of SharePoint Embedded
.DESCRIPTION
Lists the containers for a given container type of SharePoint Embedded
.PARAMETER ContainerTypeId
The container type id
#>

param(
    [Parameter(Mandatory=$true)]
    [string] $ContainerTypeId
)

Write-Host "Listing containers for $ContainerTypeId..." -ForegroundColor Cyan

Try {
    # Calls the Graph API to list the containers
    $data = Invoke-MgGraphRequest -Method GET -Uri $('https://graph.microsoft.com/beta/storage/fileStorage/containers?$filter=containerTypeId eq ' + $ContainerTypeId) -ErrorAction Stop

    # Prints the containers as JSON
    foreach($item in $data.value) {
        $json = ConvertTo-Json -InputObject $item
        $json
    }
}
Catch {
    Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
}
Enter fullscreen mode Exit fullscreen mode

This code utilizes Invoke-MgGraphRequest with the GET method to retrieve data from the specific container type endpoint using a filter for clarity. Remember to replace $ContainerTypeId with the actual ID you want to query.

By executing this code, you'll see a list of containers in JSON format, providing valuable information for managing your SharePoint Embedded environment through PowerShell automation.

Use Cases and Examples

Now that we've equipped you with the knowledge of calling SharePoint Embedded Graph API endpoints through PowerShell, let's explore some compelling real-world scenarios where this approach shines:

  • Architecture Information Management: Effortlessly manage the building blocks of your SharePoint Embedded environment. You can retrieve and modify information about containers, columns, and metadata using Graph API endpoints, providing a comprehensive view of your architecture.
  • Security Management: Proactively maintain a secure SharePoint Embedded environment. Leverage Graph API endpoints to manage containers and files, ensuring proper access controls and data protection.
  • Availability Management: Guarantee seamless access to your SharePoint Embedded resources. Utilize Graph API endpoints to perform actions like locking and unlocking containers, ensuring data integrity and availability.
  • Migration Management: Streamline the migration process for your SharePoint Embedded content. Employ Graph API endpoints to upload files, create containers, and efficiently migrate your data.
  • Advanced Analytics: Gain valuable insights into your SharePoint Embedded usage. By leveraging specific Graph API endpoints, you can access and analyze metrics that provide a deeper understanding of your environment's health and performance.

As a practical example, let's delve into a script that demonstrates how to create a new container within SharePoint Embedded. Remember, this script structure can be adapted to interact with various Graph API endpoints based on your specific needs.

<#
.SYNOPSIS
Creates a container for a given container type of SharePoint Embedded
.DESCRIPTION
Creates a container for a given container type of SharePoint Embedded
.PARAMETER Name
The name of the container
.PARAMETER Description
The description of the container
.PARAMETER ContainerTypeId
The container type id
#>

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

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

    [Parameter(Mandatory=$true)]
    [string] $ContainerTypeId
)

Write-Host "Creating $Name container..." -ForegroundColor Cyan

Try {
    $body = @{
        displayName = $Name;
        description = $Description;
        containerTypeId = $ContainerTypeId
    }
    Invoke-MgGraphRequest -Method POST -Uri 'https://graph.microsoft.com/beta/storage/fileStorage/containers' -Body $body -ErrorAction Stop

    Write-Host "$Name container created" -ForegroundColor Cyan
}
Catch {
    Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
}
Enter fullscreen mode Exit fullscreen mode

This script utilizes Invoke-MgGraphRequest with the POST method to create a new container. It constructs a body object containing the desired name, description, and container type ID. Executing this script creates a new container within your SharePoint Embedded environment, showcasing the practical power of PowerShell in conjunction with Graph API endpoints.

Conclusion

Throughout this article, we've explored the power of Microsoft Graph PowerShell in managing SharePoint Embedded environments. By leveraging the Graph API, you can automate and streamline various tasks, from architecture management to security and availability.

Key Takeaways:

  • Bridging the Gap: Microsoft Graph PowerShell provides a comprehensive set of cmdlets that fill the void left by traditional PowerShell cmdlets for SharePoint Embedded.
  • Authentication Made Easy: Seamlessly connect to Microsoft Graph using app-only access authentication for secure API interactions.
  • Leveraging Invoke-MgGraphRequest: The Invoke-MgGraphRequest cmdlet empowers you to call any Graph API endpoint with ease, providing flexibility and customization.
  • Real-World Applications: Explore a wide range of use cases, from managing architecture and security to automating migration and analytics tasks.

As you've seen, Microsoft Graph PowerShell offers a powerful and efficient way to manage your SharePoint Embedded environment. I encourage you to delve deeper into its capabilities and explore the vast possibilities it unlocks. With the ability to automate tasks, streamline processes, and gain valuable insights, Microsoft Graph PowerShell is an invaluable tool for any SharePoint Embedded administrator.

Resources

Top comments (0)