### Install gnome-keyring on Ubuntu/WSL
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/README.md
Install the `gnome-keyring` package, which is required for authentication in headless Linux environments like WSL. The `--assume-yes` flag automatically confirms the installation.
```bash
sudo apt-get install --assume-yes gnome-keyring
```
--------------------------------
### Application Defaults Configuration Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/configuration.md
Example of an application-wide app-settings.json file. This file provides default values that can be overridden by user settings or environment variables.
```json
{
"AuthenticationOptions": {
"ClientId": null,
"TenantId": null
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
}
}
```
--------------------------------
### User Settings Configuration Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/configuration.md
Example of a user-specific settings.json file. This file can override application defaults for authentication and logging.
```json
{
"AuthenticationOptions": {
"ClientId": "00000000-0000-0000-0000-000000000000",
"TenantId": "contoso.onmicrosoft.com",
"Strategy": "DeviceCode",
"Environment": "Global"
},
"Logging": {
"LogLevel": {
"Default": "Warning",
"Microsoft.Graph.Cli": "Information"
}
}
}
```
--------------------------------
### Development Setup with Device Code Authentication
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/configuration.md
Configure the CLI for development using interactive device code authentication and detailed logging. This setup is suitable for local development and debugging.
```json
{
"AuthenticationOptions": {
"Strategy": "DeviceCode"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Graph.Cli": "Debug"
}
}
}
```
```bash
mgc login
mgc users list --debug
```
--------------------------------
### Production Setup with App-Only Authentication
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/configuration.md
Configure the CLI for production environments using app-only authentication with a client certificate. This setup is suitable for unattended scenarios.
```json
{
"AuthenticationOptions": {
"ClientId": "00000000-0000-0000-0000-000000000000",
"TenantId": "contoso.onmicrosoft.com",
"Strategy": "ClientCertificate",
"ClientCertificateThumbPrint": "ABC123DEF456..."
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
}
}
```
```bash
mgc login
mgc users list
```
--------------------------------
### Batch Operations Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/command-structure.md
Perform batch operations on resources. For example, use 'delta' to get changes for users.
```bash
mgc users delta
```
--------------------------------
### License/Sku Entity Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/types-and-schemas.md
Provides an example of an available license in the organization, including its SKU ID, product name, and included service plans.
```json
{
"skuId": "84a661c4-e949-4bd2-a560-ed7766fcaf2b",
"skuPartNumber": "ENTERPRISEPACK",
"servicePlans": [
{
"servicePlanId": "a23b959c-7ce8-4cdc-9509-9eef82b6b235",
"servicePlanName": "EXCHANGE_S_ENTERPRISE"
}
]
}
```
--------------------------------
### Corrected Configuration Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/configuration.md
This example shows the correct data type for the `ClientId` within the `AuthenticationOptions`. Ensure string values are enclosed in double quotes.
```json
{
"AuthenticationOptions": {
"ClientId": "00000000-0000-0000-0000-000000000000" // String
}
}
```
--------------------------------
### Navigation Command Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/overview.md
Demonstrates how to navigate to related resources using intermediate commands in the CLI.
```bash
mgc users {user-id} messages list
```
--------------------------------
### Incorrect Configuration Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/configuration.md
This example demonstrates an incorrect configuration where `ClientId` is provided as a number instead of a string. Configuration binding failures often occur due to mismatched data types.
```json
{
"AuthenticationOptions": {
"ClientId": 12345 // Should be string
}
}
```
--------------------------------
### Install Certificates on macOS
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Run the provided command to install certificates on macOS, which may help resolve TLS/SSL certificate errors by ensuring the system has the correct certificate authorities.
```bash
/Applications/Python\ 3.x/Install\ Certificates.command
```
--------------------------------
### Device Code Login with Global Tenant
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/authentication.md
Example of logging in using the DeviceCode strategy with the 'global' tenant identifier.
```bash
# With global tenant
mgc login --strategy DeviceCode \
--tenant-id global
```
--------------------------------
### Install Microsoft Graph CLI
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/quick-start.md
Verify the installation of the Microsoft Graph CLI by checking its version. Use 'mgc --version' on Windows and './mgc --version' on macOS/Linux.
```cmd
mgc --version
```
```bash
./mgc --version
```
--------------------------------
### Users: Create
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for creating a new user.
```APIDOC
## POST /users
### Description
Creates a new user in Microsoft Graph.
### Method
POST
### Endpoint
/users
### Request Body
- **accountEnabled** (boolean) - Required - Specifies if the user account is enabled.
- **displayName** (string) - Required - The display name of the user.
- **mailNickname** (string) - Required - The mail alias for the user.
- **userPrincipalName** (string) - Required - The user principal name (e.g., user@domain.com).
- **passwordProfile** (object) - Required - Profile information for the user's password.
- **forceChangePasswordNextSignIn** (boolean) - Required - Whether the user must change their password on next sign-in.
- **password** (string) - Required - The user's password.
### Request Example
```json
{
"accountEnabled": true,
"displayName": "John Doe",
"mailNickname": "johndoe",
"userPrincipalName": "john@contoso.com",
"passwordProfile": {
"forceChangePasswordNextSignIn": true,
"password": "TempPassword@123"
}
}
```
```
--------------------------------
### Create Simple User
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example of creating a user with essential properties like account status, display name, and principal name.
```bash
mgc users create --body '{
"accountEnabled": true,
"displayName": "John Doe",
"mailNickname": "johndoe",
"userPrincipalName": "john@contoso.com",
"passwordProfile": {
"forceChangePasswordNextSignIn": true,
"password": "TempPassword@123"
}
}'
```
--------------------------------
### Device Code Login with Specific Tenant
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/authentication.md
Example of logging in using the DeviceCode strategy with a specified tenant ID.
```bash
# Device code with specific tenant
mgc login --tenant-id contoso.onmicrosoft.com
```
--------------------------------
### Create Team with Member
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example of creating a team, including an owner as a member with a specific role.
```bash
mgc teams create --body '{
"displayName": "Product Development",
"description": "Team for product development",
"members": [
{
"@odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user@odata.bind": "https://graph.microsoft.com/v1.0/users/{user-id}"
}
]
}'
```
--------------------------------
### 400 Bad Request: Missing Required Property Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Example of a 400 Bad Request error due to a missing required property.
```bash
# Missing required property
$ mgc users create --body '{"displayName":"John"}'
Error 400(invalidRequest) from API:
Missing required property: userPrincipalName
```
--------------------------------
### Teams: Create
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for creating a new team.
```APIDOC
## POST /teams
### Description
Creates a new team.
### Method
POST
### Endpoint
/teams
### Request Body
- **displayName** (string) - Required - The display name of the team.
- **description** (string) - Optional - A description for the team.
- **owners** (array) - Required - A list of users who will be owners of the team.
- **@odata.type** (string) - Required - The OData type, typically '#microsoft.graph.aadUserConversationMember'.
- **roles** (array of strings) - Required - The roles assigned to the owner, e.g., ['owner'].
- **user@odata.bind** (string) - Required - The OData binding URL for the user.
### Request Example
```json
{
"displayName": "Product Team",
"description": "Product development team",
"owners": [
{
"@odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user@odata.bind": "https://graph.microsoft.com/v1.0/users/{user-id}"
}
]
}
```
```
--------------------------------
### List User Sub-Resources
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/command-structure.md
Examples of listing various sub-resources for a user, such as messages, calendar, drive, and presence.
```bash
mgc users {user-id} messages list
mgc users {user-id} calendar get
mgc users {user-id} drive get
mgc users {user-id} onenote get
mgc users {user-id} presence get
mgc users {user-id} mail-folders list
mgc users {user-id} contacts list
mgc users {user-id} calendar-view list
mgc users {user-id} events list
mgc users {user-id} joined-teams list
mgc users {user-id} member-of list
mgc users {user-id} direct-reports list
mgc users {user-id} manager get
mgc users {user-id} managed-devices list
mgc users {user-id} owned-devices list
```
--------------------------------
### Create Group
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example of creating a security group with properties like display name and mail nickname.
```bash
mgc groups create --body '{
"displayName": "Engineering Team",
"mailEnabled": false,
"mailNickname": "engineering",
"securityEnabled": true
}'
```
--------------------------------
### Groups: Create
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for creating a new group.
```APIDOC
## POST /groups
### Description
Creates a new group.
### Method
POST
### Endpoint
/groups
### Request Body
- **displayName** (string) - Required - The display name of the group.
- **mailEnabled** (boolean) - Required - Whether the group is mail-enabled.
- **mailNickname** (string) - Required - The mail alias for the group.
- **securityEnabled** (boolean) - Required - Whether the group is a security group.
- **description** (string) - Optional - A description for the group.
### Request Example
```json
{
"displayName": "Engineering Team",
"mailEnabled": false,
"mailNickname": "engineering",
"securityEnabled": true,
"description": "Core engineering team"
}
```
```
--------------------------------
### Interactive Browser Login with Scopes
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/authentication.md
Example of logging in using the InteractiveBrowser strategy and requesting specific scopes.
```bash
# Interactive browser with scopes
mgc login --strategy InteractiveBrowser \
--client-id 00000000-0000-0000-0000-000000000000 \
--scopes User.Read Mail.Read
```
--------------------------------
### List Site Sub-Resources
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/command-structure.md
Examples of listing various sub-resources for a site, including drives, lists, columns, and content types.
```bash
mgc sites {site-id} drives list
mgc sites {site-id} lists list
mgc sites {site-id} columns list
mgc sites {site-id} content-types list
mgc sites {site-id} pages list
```
--------------------------------
### Configure gnome-keyring for Headless Environments
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/README.md
For headless environments (e.g., WSL), start the `gnome-keyring-daemon` and set a password for access token encryption. The `KEYRING_PASSWORD` can be any string.
```bash
export KEYRING_PASSWORD=any-password
printf '%s' "$KEYRING_PASSWORD" | gnome-keyring-daemon --daemonize --components=secrets --unlock
```
--------------------------------
### List Team Sub-Resources
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/command-structure.md
Examples of listing various sub-resources for a team, including channels, members, owners, and apps.
```bash
mgc teams {team-id} channels list
mgc teams {team-id} members list
mgc teams {team-id} owners list
mgc teams {team-id} group-id get
mgc teams {team-id} primary-channel get
mgc teams {team-id} apps list
```
--------------------------------
### Example Event Object
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/types-and-schemas.md
Represents a complete calendar event object with all its properties.
```json
{
"id": "AQMkADU3OTAwZWRjLXJhLWE=",
"subject": "Team Meeting",
"body": {
"contentType": "html",
"content": "
Quarterly team sync
"
},
"start": {
"dateTime": "2024-06-28T14:00:00",
"timeZone": "Pacific Standard Time"
},
"end": {
"dateTime": "2024-06-28T15:00:00",
"timeZone": "Pacific Standard Time"
},
"attendees": [
{
"emailAddress": {
"address": "john@contoso.com",
"name": "John Doe"
},
"type": "required"
}
],
"organizer": {
"emailAddress": {
"address": "jane@contoso.com",
"name": "Jane Smith"
}
},
"isOnlineMeeting": true,
"onlineMeetingUrl": "https://teams.microsoft.com/l/meetup-join/",
"isReminderOn": true,
"reminderMinutesBeforeStart": 15,
"isAllDay": false
}
```
--------------------------------
### List Group Sub-Resources
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/command-structure.md
Examples of listing various sub-resources for a group, such as members, owners, conversations, and sites.
```bash
mgc groups {group-id} members list
mgc groups {group-id} owners list
mgc groups {group-id} conversations list
mgc groups {group-id} calendar get
mgc groups {group-id} drive get
mgc groups {group-id} sites list
```
--------------------------------
### Client Certificate Login for App-Only Access
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/authentication.md
Example of logging in using the ClientCertificate strategy for application-only authentication, including certificate details.
```bash
# Client certificate for app-only access
mgc login --strategy ClientCertificate \
--client-id 00000000-0000-0000-0000-000000000000 \
--client-certificate-name MyServiceAccount \
--client-certificate-thumbprint A1B2C3D4E5F6G7H8I9J0K1L2M3N4O5P6Q7R8S9T0
```
--------------------------------
### Execute Team Action Command
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/command-structure.md
Example of executing an action command on a team resource, specifically archiving a team.
```bash
mgc teams {team-id} archive
```
--------------------------------
### Users: Assign License
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for assigning or removing licenses for a user.
```APIDOC
## POST /users/{user-id}/assignLicense
### Description
Assigns or removes licenses for a user.
### Method
POST
### Endpoint
/users/{user-id}/assignLicense
### Request Body
- **addLicenses** (array) - Optional - Licenses to add to the user.
- **skuId** (string) - Required - The SKU ID of the license to add.
- **removeLicenses** (array) - Optional - Licenses to remove from the user.
### Request Example
```json
{
"addLicenses": [
{
"skuId": "sku-id-value"
}
],
"removeLicenses": []
}
```
```
--------------------------------
### XML Output Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/output-formats.md
Utilize the XML output format for integration with SOAP/XML-based systems or legacy applications. The output is structured as an XML document.
```bash
mgc users list --top 1 --output XML
```
```xml
12345678-1234-1234-1234-123456789012John Doejohn@contoso.comjohn@contoso.comtrue
```
--------------------------------
### Files/Drive Items: Create Folder
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for creating a new folder within a drive item.
```APIDOC
## POST /drives/{drive-id}/items/{item-id}/children
### Description
Creates a new folder as a child of a specified drive item.
### Method
POST
### Endpoint
/drives/{drive-id}/items/{item-id}/children
### Request Body
- **name** (string) - Required - The name of the new folder.
- **folder** (object) - Required - An empty object to indicate that this item is a folder.
### Request Example
```json
{
"name": "New Folder",
"folder": {}
}
```
```
--------------------------------
### Create Team Request Body
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example of a request body for creating a new team, including display name, description, and initial owners.
```bash
mgc teams create --body '{
"displayName": "Product Team",
"description": "Product development team",
"owners": [
{
"@odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user@odata.bind": "https://graph.microsoft.com/v1.0/users/{user-id}"
}
]
}'
```
--------------------------------
### App-only Login with Certificate
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Authenticate using a client certificate for app-only flows. Ensure the certificate is correctly installed and referenced.
```bash
mgc login --strategy ClientCertificate --client-id YOUR_CLIENT_ID
```
--------------------------------
### Login with Client Certificate Name
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Authenticate using a client certificate by specifying its name. This is useful when the certificate is installed in the system store.
```bash
mgc login --strategy ClientCertificate \
--client-certificate-name "CorrectCertName"
```
--------------------------------
### Program.cs Entry Point Initialization
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/overview.md
The Program.cs file serves as the application's entry point, responsible for setting up the CLI environment. This includes initializing the console encoding, command-line parser, dependency injection container, authentication providers, HTTP client, serialization factories, and event logging.
```csharp
public class Program
{
public static void Main(string[] args)
{
// Entry point; handles "me" command alias replacement and invokes the command parser
BuildCommandLine().InvokeAsync(args).Wait();
}
private static CommandLineBuilder BuildCommandLine()
{
var commandLineBuilder = new CommandLineBuilder();
// Construct the root command with all subcommands and middleware
var rootCommand = BuildRootCommand();
commandLineBuilder.AddCommand(rootCommand);
// Configure middleware, options, etc.
commandLineBuilder.UseDefaults();
return commandLineBuilder;
}
private static Command BuildRootCommand()
{
// Placeholder for building the root command and its subcommands
var rootCommand = new RootCommand("Microsoft Graph CLI");
// Add subcommands here...
return rootCommand;
}
// Other methods like CreateHostBuilder, ConfigureAppConfiguration, GetExceptionMessage, GetExceptionExitCode would be defined here.
}
```
--------------------------------
### JMESPath: String Operations - Substring
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/output-formats.md
Extract a portion of a string. This example gets the first 5 characters of each user's email address.
```bash
# Get substring
mgc users list --query "value[].substr(mail, 0, 5)"
```
--------------------------------
### Login with Client Certificate Thumbprint
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Authenticate using a client certificate by providing its thumbprint. Ensure the thumbprint is accurate and matches an installed certificate.
```bash
mgc login --client-certificate-thumbprint "ABCD1234..."
```
--------------------------------
### JMESPath: Advanced - Top N and Sort
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/output-formats.md
Combine sorting and slicing to retrieve a specific number of top items. This example gets the top 5 users sorted by name.
```bash
# Get top 5 users by name
mgc users list --top 100 --query "sort_by(value, &displayName)[0:5].displayName"
```
--------------------------------
### Graph CLI Configuration Merge Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/configuration.md
Demonstrates how configuration values are merged from different sources, with command-line parameters taking precedence, followed by environment variables, user settings, and app settings.
```text
app-settings.json: Strategy = "InteractiveBrowser"
settings.json: Strategy = "DeviceCode"
env var: MGC_AuthenticationOptions__Strategy = "ClientCertificate"
# Effective value: "ClientCertificate" (env var wins)
```
--------------------------------
### Get Item Counts
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/quick-start.md
Use the `count get` command to retrieve the number of items for a resource.
```bash
mgc users count get
mgc groups count get
mgc teams count get
```
--------------------------------
### 400 Bad Request: Malformed JSON Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Example of a 400 Bad Request error due to malformed JSON.
```bash
# Malformed JSON
$ mgc users create --body '{"displayName":"John"' # Missing closing brace
Error: Invalid JSON in request body
```
--------------------------------
### Assign License to User Request Body
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example of a request body for assigning and removing licenses for a user, specifying SKU IDs.
```bash
mgc users {user-id} assign-license --body '{
"addLicenses": [
{
"skuId": "sku-id-value"
}
],
"removeLicenses": []
}'
```
--------------------------------
### Managing Multiple Tenants with Command Line Configuration Files
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/configuration.md
Switch between tenants by copying different `settings.json` configuration files to the CLI's configuration directory. This method allows for distinct configurations per tenant.
```bash
# Create config for tenant 1
cp ~/config1.json ~/.config/Microsoft.Graph.Cli/settings.json
mgc login
mgc users list > tenant1-users.json
# Create config for tenant 2
cp ~/config2.json ~/.config/Microsoft.Graph.Cli/settings.json
mgc logout
mgc login
mgc users list > tenant2-users.json
```
--------------------------------
### 400 Bad Request: Invalid Property Type Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Example of a 400 Bad Request error due to an invalid property type.
```bash
# Invalid property type
$ mgc users create --body '{"accountEnabled":"true"}' # Should be boolean
Error 400(invalidRequest) from API:
Invalid value for property: accountEnabled
```
--------------------------------
### Create Folder Request Body
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example of a request body for creating a new folder within a drive item, specifying the folder name.
```bash
mgc drives {drive-id} items {item-id} children create --body '{
"name": "New Folder",
"folder": {}
}'
```
--------------------------------
### Using Global Help Option
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/command-structure.md
Display help information for a specific command. The `--help` option provides detailed usage instructions.
```bash
mgc users list --help
```
--------------------------------
### Create Event Request Body
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example of a request body for creating a calendar event, including subject, start/end times, reminder settings, and attendees.
```bash
mgc users {user-id} events create --body '{
"subject": "Team Meeting",
"start": {
"dateTime": "2024-06-27T14:00:00",
"timeZone": "UTC"
},
"end": {
"dateTime": "2024-06-27T15:00:00",
"timeZone": "UTC"
},
"isReminderOn": true,
"reminderMinutesBeforeStart": 15,
"attendees": [
{
"emailAddress": {
"address": "attendee@contoso.com",
"name": "Team Member"
},
"type": "required"
}
]
}'
```
--------------------------------
### Create Team Channel Request Body
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example of a request body for creating a new channel within a team, specifying display name and description.
```bash
mgc teams {team-id} channels create --body '{
"displayName": "Announcements",
"description": "Team announcements channel"
}'
```
--------------------------------
### CSV Output Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/output-formats.md
Use the CSV output format for easy import into spreadsheets or for automated data processing. Nested objects are flattened.
```bash
mgc users list --top 2 --output CSV
```
```csv
id,displayName,mail,userPrincipalName,accountEnabled
12345678-1234-1234-1234-123456789012,John Doe,john@contoso.com,john@contoso.com,true
87654321-4321-4321-4321-210987654321,Jane Smith,jane@contoso.com,jane@contoso.com,true
```
--------------------------------
### Resolve 404 Not Found: Use Correct ID
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Illustrates using the correct resource ID to get a resource, resolving 404 Not Found errors.
```bash
# Use correct ID:
mgc users "{correct-id}" get
```
--------------------------------
### Login with Client ID, Tenant ID, and Scopes
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/README.md
Authenticate using your application's client ID, tenant ID, and specified scopes for API access.
```bash
mgc login --client-id `YOUR_CLIENT_ID` --tenant-id `YOUR_TENANT_ID` --scopes User.ReadWrite --scopes Mail.ReadWrite
```
--------------------------------
### Install CA Certificates on Linux
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Ensure the 'ca-certificates' package is installed on Linux systems to resolve TLS/SSL certificate errors. This package provides necessary root CA certificates for secure connections.
```bash
sudo apt-get install ca-certificates
```
--------------------------------
### Resolve 404 Not Found: Get Correct ID
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Shows how to retrieve the correct resource ID using `list` and `jq` to resolve 404 Not Found errors.
```bash
# Get correct ID:
users=$(mgc users list --select "id,displayName" --filter "displayName eq 'John Doe'")
echo "$users" | jq '.value[0].id'
```
--------------------------------
### Get Security Alerts
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/overview.md
Retrieve a list of security alerts.
```bash
mgc security alerts list
```
--------------------------------
### Get Drive
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/samples/6-Drives.md
Retrieves details for a specific drive using its ID.
```APIDOC
## Get Drive
### Description
Retrieves details for a specific drive using its ID.
### Method
GET
### Endpoint
/drives/{drive-id}
### Parameters
#### Path Parameters
- **drive-id** (string) - Required - The unique identifier of the drive.
### Response
#### Success Response (200)
- **id** (string) - The unique identifier of the drive.
- **driveType** (string) - The type of the drive (e.g., 'personal', 'business').
- **owner** (object) - Information about the owner of the drive.
### Response Example
{
"id": "",
"driveType": "personal",
"owner": {
"user": {
"displayName": "User Name"
}
}
}
```
--------------------------------
### Download and Extract CLI Package
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/README.md
Use curl to download the installation package and tar to extract it. Replace `` and `` with the actual download URL and package name.
```bash
curl -LO && tar -xzf
```
--------------------------------
### Test Graph CLI Authentication
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/configuration.md
Verify your authentication setup by attempting to retrieve your user profile. If an error occurs, log out and log back in to re-authenticate.
```bash
# Test authentication
mgc users me get
# If error "Token acquisition failed":
mgc logout
mgc login
```
--------------------------------
### View Supported Authentication Strategies
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/README.md
Run this command to see the available authentication strategies for the CLI. The default is Device Code.
```bash
mgc login --help
```
--------------------------------
### Get Authenticated User
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/overview.md
Retrieve details of the currently authenticated user.
```bash
mgc users me get
```
--------------------------------
### Groups: Update
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for updating an existing group.
```APIDOC
## PATCH /groups/{group-id}
### Description
Updates properties of an existing group.
### Method
PATCH
### Endpoint
/groups/{group-id}
### Request Body
- **displayName** (string) - Optional - The updated display name of the group.
- **description** (string) - Optional - The updated description of the group.
### Request Example
```json
{
"displayName": "Updated Group Name",
"description": "Updated description"
}
```
```
--------------------------------
### Resolve 404 Not Found: Verify Resource Exists
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Demonstrates how to verify if a resource exists using a filter to resolve 404 Not Found errors.
```bash
# Verify resource exists:
mgc users list --filter "userPrincipalName eq 'john@contoso.com'"
```
--------------------------------
### View CLI Configuration
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/quick-start.md
Displays the content of the CLI settings file.
```bash
cat ~/.config/Microsoft.Graph.Cli/settings.json
```
--------------------------------
### Groups: Add Member
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for adding a member to a group.
```APIDOC
## POST /groups/{group-id}/members
### Description
Adds a member to a group.
### Method
POST
### Endpoint
/groups/{group-id}/members
### Request Body
- **@odata.type** (string) - Required - The OData type, typically '#microsoft.graph.directoryObject'.
- **id** (string) - Required - The ID of the member to add.
### Request Example
```json
{
"@odata.type": "#microsoft.graph.directoryObject",
"id": "user-id"
}
```
```
--------------------------------
### Login with Default Client ID and Tenant ID
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/samples/1-Login.md
Use this command to log in with default client and tenant IDs. Specify the required scopes for your operations.
```sh
mgc login --scopes User.ReadWrite Mail.ReadWrite
```
--------------------------------
### Get Group Details
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/samples/3-UsersAndGroups.md
Retrieves detailed information for a specific group using its ID.
```sh
mgc groups get --group-id
```
--------------------------------
### Teams: Send Message
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for sending a message to a team channel.
```APIDOC
## POST /teams/{team-id}/channels/{channel-id}/messages
### Description
Sends a message to a specific channel in a team.
### Method
POST
### Endpoint
/teams/{team-id}/channels/{channel-id}/messages
### Request Body
- **body** (object) - Required - The content of the message.
- **content** (string) - Required - The message content.
- **contentType** (string) - Required - The content type of the message (e.g., 'html', 'text').
### Request Example
```json
{
"body": {
"content": "Hello team!",
"contentType": "html"
}
}
```
```
--------------------------------
### Create User with Required Properties
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Create a new user by providing all the necessary required properties. Missing required properties will result in an error.
```bash
mgc users create --body '{
"accountEnabled": true,
"displayName": "John",
"mailNickname": "john",
"userPrincipalName": "john@contoso.com",
"passwordProfile": {"password": "TempPassword@123"}
}'
```
--------------------------------
### Users: Change Password
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for changing a user's password.
```APIDOC
## POST /users/{user-id}/changePassword
### Description
Changes the password for a user.
### Method
POST
### Endpoint
/users/{user-id}/changePassword
### Request Body
- **currentPassword** (string) - Required - The user's current password.
- **newPassword** (string) - Required - The user's new password.
### Request Example
```json
{
"currentPassword": "OldPassword@123",
"newPassword": "NewPassword@456"
}
```
```
--------------------------------
### Users: Update
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for updating an existing user's properties.
```APIDOC
## PATCH /users/{user-id}
### Description
Updates properties of an existing user.
### Method
PATCH
### Endpoint
/users/{user-id}
### Request Body
- **displayName** (string) - Optional - The updated display name of the user.
- **jobTitle** (string) - Optional - The updated job title of the user.
- **officeLocation** (string) - Optional - The updated office location of the user.
### Request Example
```json
{
"displayName": "Jane Doe",
"jobTitle": "Senior Engineer",
"officeLocation": "Building B"
}
```
```
--------------------------------
### Execute User Action Commands
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/command-structure.md
Demonstrates executing action commands on user resources, such as sending an email. Requires a JSON payload for the email body.
```bash
mgc users {user-id} send-mail --body '{
"message": {
"subject": "Welcome",
"body": {
"contentType": "text",
"content": "Welcome to the team!"
},
"toRecipients": [{
"emailAddress": {
"address": "colleague@contoso.com"
}
}]
}
}'
```
--------------------------------
### Get User Messages
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/overview.md
List messages for a specific user, selecting only the subject, from, and receivedDateTime properties.
```bash
mgc users {user-id} messages list --select "subject,from,receivedDateTime"
```
--------------------------------
### Example Team Object
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/types-and-schemas.md
Represents a typical Microsoft Teams team object with its key properties.
```json
{
"id": "12345678-abcd-abcd-abcd-123456789012",
"displayName": "Product Team",
"description": "Team for product development",
"isArchived": false,
"createdDateTime": "2023-03-15T14:20:00Z"
}
```
--------------------------------
### Example Group Object
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/types-and-schemas.md
Represents a typical Azure AD group object with its key properties.
```json
{
"id": "87654321-4321-4321-4321-210987654321",
"displayName": "Engineering Team",
"description": "Core engineering team",
"mail": "engineering@contoso.com",
"mailEnabled": true,
"securityEnabled": false,
"createdDateTime": "2023-06-01T09:00:00Z"
}
```
--------------------------------
### List Resources with Options
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/command-structure.md
Lists items in a collection with options for limiting results, filtering, selecting properties, expanding related entities, sorting, and specifying output format.
```bash
mgc users list --top 10 --select "displayName,mail" --output JSON
mgc groups list --filter "displayName eq 'Engineering'" --expand members
```
--------------------------------
### Mail/Messages: Create Draft Message
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for creating a draft email message.
```APIDOC
## POST /users/{user-id}/messages
### Description
Creates a draft email message in the specified user's mailbox.
### Method
POST
### Endpoint
/users/{user-id}/messages
### Request Body
- **subject** (string) - Required - The subject of the draft message.
- **body** (object) - Required - The body of the draft message.
- **contentType** (string) - Required - The content type of the body (e.g., 'html', 'text').
- **content** (string) - Required - The draft message content.
- **toRecipients** (array) - Required - A list of recipients.
- **emailAddress** (object) - Required - The email address of the recipient.
- **address** (string) - Required - The email address.
- **isDraft** (boolean) - Required - Set to true to indicate this is a draft message.
### Request Example
```json
{
"subject": "Draft Email",
"body": {
"contentType": "text",
"content": "This is a draft message"
},
"toRecipients": [
{
"emailAddress": {
"address": "recipient@contoso.com"
}
}
],
"isDraft": true
}
```
```
--------------------------------
### Create a User
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/overview.md
Create a new user with specified properties. Ensure all required fields in the body are provided.
```bash
mgc users create --body "{
"accountEnabled": true,
"displayName": "John Doe",
"mailNickname": "johndoe",
"userPrincipalName": "johndoe@contoso.com",
"passwordProfile": {
"forceChangePasswordNextSignIn": true,
"password": "Temp@1234567"
}
}"
```
--------------------------------
### Mail/Messages: Send Mail
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for sending an email from a user's mailbox.
```APIDOC
## POST /users/{user-id}/sendMail
### Description
Sends an email message from the specified user's mailbox.
### Method
POST
### Endpoint
/users/{user-id}/sendMail
### Request Body
- **message** (object) - Required - The email message to send.
- **subject** (string) - Required - The subject of the email.
- **body** (object) - Required - The body of the email.
- **contentType** (string) - Required - The content type of the body (e.g., 'html', 'text').
- **content** (string) - Required - The email content.
- **toRecipients** (array) - Required - A list of recipients.
- **emailAddress** (object) - Required - The email address of the recipient.
- **address** (string) - Required - The email address.
- **ccRecipients** (array) - Optional - A list of CC recipients.
- **emailAddress** (object) - Required - The email address of the CC recipient.
- **address** (string) - Required - The email address.
### Request Example
```json
{
"message": {
"subject": "Meeting Scheduled",
"body": {
"contentType": "html",
"content": "
Our meeting is scheduled for 3 PM.
"
},
"toRecipients": [
{
"emailAddress": {
"address": "recipient@contoso.com"
}
}
],
"ccRecipients": [
{
"emailAddress": {
"address": "cc@contoso.com"
}
}
]
}
}
```
```
--------------------------------
### Teams: Create Channel
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for creating a new channel within a team.
```APIDOC
## POST /teams/{team-id}/channels
### Description
Creates a new channel within a specified team.
### Method
POST
### Endpoint
/teams/{team-id}/channels
### Request Body
- **displayName** (string) - Required - The display name of the channel.
- **description** (string) - Optional - A description for the channel.
### Request Example
```json
{
"displayName": "Announcements",
"description": "Team announcements channel"
}
```
```
--------------------------------
### Configure Application Defaults with app-settings.json
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/overview.md
Use app-settings.json to define default application settings, including authentication client and tenant IDs, and logging levels.
```json
{
"AuthenticationOptions": {
"ClientId": "client-id-value",
"TenantId": "tenant-id-value"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
}
}
```
--------------------------------
### Check Command Help
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/quick-start.md
Displays help information for the CLI, commands, or specific actions.
```bash
# General help
mgc --help
```
```bash
# Command help
mgc users --help
```
```bash
# Specific action help
mgc users create --help
```
--------------------------------
### OData Error Format Example
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Illustrates the standard OData error format returned by the API.
```text
Error 404(itemNotFound) from API:
Item not found
```
--------------------------------
### Basic Syntax for mgc login
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/authentication.md
Shows the general structure and available parameters for the `mgc login` command.
```bash
mgc login [--strategy STRATEGY] \
[--client-id CLIENT_ID] \
[--tenant-id TENANT_ID] \
[--scopes SCOPE ...] \
[--client-certificate-name NAME] \
[--client-certificate-thumbprint THUMBPRINT]
```
--------------------------------
### Events/Calendar: Create Event
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Example request body for creating a new event in a user's calendar.
```APIDOC
## POST /users/{user-id}/events
### Description
Creates a new event in the specified user's calendar.
### Method
POST
### Endpoint
/users/{user-id}/events
### Request Body
- **subject** (string) - Required - The subject of the event.
- **start** (object) - Required - The start time of the event.
- **dateTime** (string) - Required - The date and time in ISO 8601 format.
- **timeZone** (string) - Required - The time zone of the start time.
- **end** (object) - Required - The end time of the event.
- **dateTime** (string) - Required - The date and time in ISO 8601 format.
- **timeZone** (string) - Required - The time zone of the end time.
- **isReminderOn** (boolean) - Required - Whether a reminder is set for the event.
- **reminderMinutesBeforeStart** (integer) - Optional - The number of minutes before the event start time for the reminder.
- **attendees** (array) - Optional - A list of attendees for the event.
- **emailAddress** (object) - Required - The email address of the attendee.
- **address** (string) - Required - The email address.
- **name** (string) - Optional - The name of the attendee.
- **type** (string) - Required - The type of attendee (e.g., 'required', 'optional').
### Request Example
```json
{
"subject": "Team Meeting",
"start": {
"dateTime": "2024-06-27T14:00:00",
"timeZone": "UTC"
},
"end": {
"dateTime": "2024-06-27T15:00:00",
"timeZone": "UTC"
},
"isReminderOn": true,
"reminderMinutesBeforeStart": 15,
"attendees": [
{
"emailAddress": {
"address": "attendee@contoso.com",
"name": "Team Member"
},
"type": "required"
}
]
}
```
```
--------------------------------
### Login with Client Certificate Authentication
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/authentication.md
Authenticate using a client certificate by providing the strategy, client ID, and the certificate's thumbprint. Ensure the certificate is installed in the system store and the thumbprint is correct.
```bash
mgc login --strategy ClientCertificate \
--client-id ... \
--client-certificate-thumbprint ABC123...
```
--------------------------------
### Basic Command Structure
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/overview.md
Illustrates the fundamental hierarchical structure of Microsoft Graph CLI commands.
```bash
mgc ...
```
--------------------------------
### JMESPath: String Operations - Uppercase
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/output-formats.md
Perform string transformations. This example converts display names to uppercase.
```bash
# Convert to uppercase
mgc users list --query "value[].to_upper(displayName)"
```
--------------------------------
### Create User with Optional Properties
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Create a new user, optionally including properties like `jobTitle` or `officeLocation`. These fields can be omitted.
```bash
mgc users create --body '{
"accountEnabled": true,
"displayName": "John",
"mailNickname": "john",
"userPrincipalName": "john@contoso.com",
"passwordProfile": {"password": "TempPassword@123"}
# "jobTitle", "officeLocation", etc. are optional
}'
```
--------------------------------
### Get Operation
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/command-structure.md
Retrieves a single item by its ID. Allows for selecting specific properties and expanding related entities.
```APIDOC
## Get Operation
### Description
Retrieves a single item by its ID. Allows for selecting specific properties and expanding related entities.
### Syntax
`mgc {id} get`
### Options
- `--select ...` — Select specific properties
- `--expand ...` — Expand related entities
- `--output ` — Output format (default: JSON)
- `--query ` — JMESPath filter
### Example
```bash
mgc users {user-id} get --select "displayName,mail,jobTitle"
mgc teams {team-id} get --expand "channels,members"
```
```
--------------------------------
### List All Users
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/samples/3-UsersAndGroups.md
Retrieves all users, selecting specific properties. Use the --all flag for comprehensive listing.
```sh
mgc users list --select "id, displayName, OfficeLocation, BusinessPhones" --all
```
--------------------------------
### Get Messages from Chat
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/samples/4-Teams.md
Retrieve messages from a specific chat by providing the chat ID. Ensure you have the correct ChatId.
```sh
mgc chats messages list --chat-id
```
--------------------------------
### Get list of 1:1 chats
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/samples/4-Teams.md
Use this command to retrieve a list of all 1:1 chats associated with the authenticated user.
```sh
mgc chats list
```
--------------------------------
### Configure System Proxy on Windows
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/error-reference.md
Configure the system-wide proxy settings on Windows using the 'netsh' command. This is useful for resolving 'Failed to connect through proxy' errors when a proxy server is required.
```bash
netsh winhttp set proxy proxy-server:port
```
--------------------------------
### Create Group with Array of Owners
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/request-bodies.md
Shows how to use JSON arrays for multi-valued properties, such as a list of group owners.
```bash
mgc groups create --body '{
"displayName": "Sales Team",
"owners": [
{
"@odata.type": "#microsoft.graph.directoryObject",
"id": "owner-id-1"
},
{
"@odata.type": "#microsoft.graph.directoryObject",
"id": "owner-id-2"
}
]
}'
```
--------------------------------
### Set Client ID and Tenant ID in Windows CMD
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/configuration.md
Use the 'set' command in Windows Command Prompt (CMD) to define environment variables for Client ID and Tenant ID. The naming convention includes the MGC_ prefix and double underscores. Run 'mgc login' to apply the settings.
```cmd
set MGC_AuthenticationOptions__ClientId=00000000-0000-0000-0000-000000000000
set MGC_AuthenticationOptions__TenantId=contoso.onmicrosoft.com
mgc login
```
--------------------------------
### Login using Microsoft Graph CLI
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/README.md
After setting up the environment and keyring, you can log in to the Microsoft Graph CLI using the `mgc login` command.
```bash
mgc login
```
--------------------------------
### List Application Registrations
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/samples/2-TenantInformation.md
Retrieves a list of application registrations in the tenant. Use the --select parameter to filter the returned properties.
```sh
mgc applications list --select "DisplayName, id, SignInAudience"
```
--------------------------------
### JMESPath: Array Length
Source: https://github.com/microsoftgraph/msgraph-cli/blob/main/_autodocs/api-reference/output-formats.md
Calculate the number of items in an array. This example counts the total number of users returned.
```bash
# Count returned users
mgc users list --query "length(value)"
```