Git Product home page Git Product logo

msgraph-sdk-powershell's Introduction

Microsoft Graph PowerShell
Microsoft Graph PowerShell

Consume Microsoft Graph resources directly from your PowerShell scripts

The Microsoft Graph PowerShell SDK is made up of a set of modules that enable you to interact with the Microsoft Graph API using PowerShell commands. The modules consist of commands that act as wrappers for the API, allowing you to access all the features and functionality of the API through PowerShell.

Modules | Getting Started | API Version | Notes | Troubleshooting | Known Issues | Feedback | License

Modules

The table below contains links to our latest and preview versions of the Microsoft Graph module. The meta modules will install all the service modules as their dependencies.

Module Latest Preview
Microsoft.Graph mg -
Microsoft.Graph.Beta mgbeta -

See Microsoft Graph PowerShell modules for a list of all modules supported by this repository.

Getting Started

1. Installation

Microsoft Graph PowerShell module is published on PowerShell Gallery. Installing is as simple as:

Install-Module Microsoft.Graph

Run Install-Module with -AllowClobber and -Force parameters if you run into command name conflicts when upgrading to older versions of the module. This may be the case when upgrading from v1.x to v2.x:

Install-Module Microsoft.Graph -AllowClobber -Force

See Install the Microsoft Graph PowerShell Module guide for detailed installation instructions.

2. Authentication

The module supports two main types of authentication:

Delegated access

Get access to Microsoft Graph resources on behalf of a user.

# Using interactive authentication.
Connect-MgGraph -Scopes "User.ReadBasic.All", "Application.ReadWrite.All"

App-only access (client credentials grant flow)

Get access to Microsoft Graph resources using the identity on an app and not on behalf of a user.

# Using -CertificateThumbprint
Connect-MgGraph -ClientId "YOUR_APP_ID" -TenantId "YOUR_TENANT_ID" -CertificateThumbprint "YOUR_CERT_THUMBPRINT"

See Authentication for more information on the usage of Connect-MgGraph.

3. List users in your tenant

Get-MgUser -Top 10 -Property Id, DisplayName, BusinessPhones | Format-Table Id, DisplayName, BusinessPhones

4. Filter a user in your tenant

$User = Get-MgUser -Filter "displayName eq 'Megan Bowen'"

5. Create a new app registration

New-MgApplication -DisplayName "ScriptedGraphPSApp" `
                  -SignInAudience "AzureADMyOrg" `
                  -Web @{ RedirectUris = "https://localhost"}

6. Sign out of the current logged-in context i.e. app only or delegated access

Disconnect-MgGraph

API Version

Install Microsoft.Graph.Beta module to commands that call Microsoft Graph Beta API endpoint.

Install-Module Microsoft.Graph.Beta
# Consume Microsoft Graph beta resources.
Connect-MgGraph
$Users = Get-MgBetaUser

Notes

Upgrading to v2

The following breaking changes have been introduced between v1.x and v2.x:

  • Dropped profile support.
  • Dropped support for -ForceRefresh on Connect-MgGraph.
  • Renamed beta command names from <Verb>-Mg<Noun> to <Verb>-MgBeta<Noun>.
  • Renamed DeviceManagement.Enrolment module to DeviceManagement.Enrollment.
  • Moved directory role and entitlement management commands from DeviceManagement.Enrollment to Identity.Governance module.
  • Changed beta namespace from Microsoft.Graph.PowerShell.Models.<Entity> to Microsoft.Graph.Beta.PowerShell.Models.<Entity>.
  • Changed -AccessToken type on Connect-MgGraph from String to SecureString.

See the v2 upgrade guide for more details.

Troubleshooting

Permission Related Errors

When working with various operations in the Graph, you may encounter an error such as "Insufficient privileges to complete the operation." For example, this particular error can occur when using the New-MgApplication command if the appropriate permissions are not granted.

If permission-related errors occur and the signed-in user/app has been granted the appropriate permissions to perform the operation, you can explicitly fetch a new access token by running Disconnect-MgGraph, then Connect-MgGraph. This will trigger a refresh of the access token in your cache. Microsoft Authentication Library (MSAL) will only refresh access tokens in your cache if they have expired (usually an hour).

See Microsoft Graph API Permissions Reference for more details.

Common Errors

See our troubleshooting guide for a detailed view of how to troubleshoot common errors when using Microsoft Graph.

Known Issues

  • Using the -Property {PropertyName} parameter will not select the property as the output of the command. All commands return CLR objects, and customers should pipe the command outputs to Format-Table or Select-Object to return individual properties.

  • Customers upgrading from previous versions of the SDK may encounter auth prompts on every command call. If this happens, one can use the following steps to reset their token cache:

    • Use Disconnect-MgGraph to sign out of the current session.
    • Run Remove-Item "$env:USERPROFILE\.mg" -Recurse -Force to delete your token cache.
    • Run Connect-MgGraph to reconstruct a clean token cache.

Feedback

If you find any bugs when using the Microsoft Graph PowerShell modules, please file an issue on our GitHub issues page.

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

License

Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT license.

msgraph-sdk-powershell's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

msgraph-sdk-powershell's Issues

Connect using BYOT via a Managed Identity in Azure Functions

I have tons of use cases for running Powershell scripts in Azure Functions. What I do at the moment is obtain my Managed Identity bearer token (which I have previously granted permissions to) and the use the Invoke-WebRequest commandlet against the raw Graph API.
It would be great if as part of the Connect commandlet I was able to either pass in my already obtained bearer token, or even maybe ask the Connect commandlet to go get it for me.
AB#5613

Get current scope(s)

Consider adding a cmdlet to list the current scopes and/or the token. Will be useful for troubleshooting purposes and avoiding 401 errors.

Uploading user photo

Hi!
First off great job on this new PS "sdk", I think it looks super promising!
Now the question: I'm trying to upload the user's picture, which I think will be a common scenarios for IT pros around the world.
I'm now sure how I should pass the photo binaries however, I've tried something like that and a few variations but it doesn't seem to be working.

update-userphoto -UserId ef1c916a-3135-4417-ba27-8eb7bd084193 -BodyParameter ([System.IO.File]::ReadAllBytes("C:\Users\vince\Desktop\00003IMG_00003_BURST20170402115324.jpg"))

At this point I'm not sure whether I missed something (hence the question) or whether this feature is currently missing in the SDK.
I'm running the beta SDK, updated/installed today.
Thanks for the help!

Push AutoREST config down to the module level

Currently AutoREST configuration is done at the global project level. This is not going to scale. We would like to create config files for each module so that individual teams can control the generation of the cmdlets for their service.

Validate scopes and better error handling

So this one is on me, but can we have proper error messages and some validation on the Scopes parameter? Here's what happens if I mistype the scope level (Mail.Read.All instead of Mail.Read):

image

Of course if I remove it or fix the typo it works fine.

Better error handling throughout the module is needed IMO...

Encrypt tokens!

Any particular reason why you are storing the tokens in unencrypted form on the hard drive? Hardly the best security practice.

I understand that you might be using this for ensuring session longevity and such, but at least store them as secure string, or use the cred man or something. On a related note, why arent you leveraging the ADAL/MSAL token cache?

AB#4594

Connect-Graph : AADSTS50196: The server terminated an operation because it encountered a loop while processing a request.

Hi,
when running Connect-Graph I am getting an error:

Connect-Graph : AADSTS50196: The server terminated an operation because it encountered a loop while processing a request

I am using proxy

[system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy('http://proxy.fqdn.com:8080')
[system.net.webrequest]::defaultwebproxy.credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
[system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true

Define DefaultDisplayPropertySet for types

Suggestion to add DefaultDisplayPropertySet for objects returned from Microsoft Graph. Currently tested commands have all properties displayed in table format, many of which are not populated with any information. This requires use of "| select-object -property propA, propB, etc." (or "| format-list ...") to display the information desired.

Example commands tested: Get-Group, Get-User.

For reference implementation:
PowerShell - Defining Default Member Sets for Objects

PowerShell - Extending properties for obejcts - Property Sets

Define proper naming strategy for *.Actions and *.Functions cmdlets

Currently, some generated cmdlets in *.Actions & *.Functions modules have duplicate names with cmdlets from other modules. This results in a cmdlet name conflict when generating the roll-up module.
e.g.
Get-Site in Sites.Site module and Get-Site in Sites.Functions module.

Disconnect-Graph doesn't work unless you close the powershell session

Steps to repro:

Call Connect-Graph and sign in.
Call Disconnect-Graph
Call Connect-Graph again.

Observed behavior

You will automatically get logged in and the old token cache will be recreated on disk.

Expected behavior

You will be asked to log in again.

If you close the PowerShell terminal after doing Disconnect-Graph then next time you open the PowerShell window Connect-Graph will work as normal. I think we just need to re-create the Application upon doing Disconnect-Graph.

Add support for beta module generation.

Add support for generation beta modules by specifying graphVersion query option to Graph Slice service. The generated Graph beta module names should be in the form of Microsoft.Graph.Beta.*.

Simplify the number of properties returned by cmdlets

Currently, all cmdlets return all properties of their response object as part of their response. This forces most customers to pipe cmdlet with | select prop1, prop2, just to get common properties like ids, names e.t.c. It would be nice to have the cmdlets return a bare minimum number of useful properties from their response object.

Add cmdlet prefix

As discussed briefly the other day on the call, you should consider adding an unique prefix to all the cmdlets. This will not only make them easier to identify with the module, but avoid clashes with existing cmdlets. Prime examples being Get-User and Get-Group - both of these are heavily used in Exchange/Exchange Online PowerShell. And since support for Exchange management tasks in the Graph is still non-existent, it's very likely that people will use both the ExO cmdlets and the Graph module in the same PS session.

Considering the sheer number of cmdlets in the module, you're bound to have other duplicates as well.

Documentation issues - missing TenantID and Mail.Read scope

Hi, I was testing the steps mentioned here. I was getting several errors and was able to fix them. Reporting them here in case documentation needs to be updated.

Issue 1:
Connect-Graph -ClientId 'ID' -Scopes 'user.read, Calendars.Read, Files.Read'. Based on my tests, I think the TenantID is also needed otherwise, I receive an error.

image

With TenantID, it succeeded.

Issue 2:
Get-MeMessage -Top 10 -Skip 10 -Select 'Id, Subject, CreatedDateTime' | Format-Table CreatedDateTime, Subject, Id. This example returns your messages, but for this to work, we need to add 'Mail.Read' to the scopes in the previous step. Otherwise, you will get an 'Access Denied' error.

image

So, to sum up, I needed to run this:
Connect-Graph -ClientId 'ID' -Scopes 'user.read, Calendars.Read, Files.Read, Mail.Read' -TenantID 'tenantID' instead of Connect-Graph -ClientId 'ID' -Scopes 'user.read, Calendars.Read, Files.Read'

Add Custom New-GroupMember cmdlet

  1. Define infrastructure to add custom cmdlets to generated modules.
  2. Add a custom New-GroupMember cmdlet to Groups.DirectoryObject module.

Remove anyof from OpenAPI document using apislice code

Autorest generator doesn't support anyof keyword. OpenAPI doc corresponding to Graph OData metadata contains usage of anyof keyword to represent nullable fields. This task is to remove anyof keyword from openapi doc to facilitate code generation using Autorest.

Get CalendarView query parameters

In which parameter do i define the query parameters?

PS C:\WINDOWS\system32> $calendar = Get-UserCalendar -UserId $Me
PS C:\WINDOWS\system32> Get-UserCalendarView -UserId $Me -CalendarId $calendar.Id
Get-UserCalendarView : This request requires a time window specified by the query string parameters StartDateTime and EndDateTime.
At line:1 char:1
+ Get-UserCalendarView -UserId $Me -CalendarId $calendar.Id
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: ({ UserId = 9ad1...= , Select =  }:<>f__AnonymousType20`8) [Get-UserCalendarView_List], Exception
    + FullyQualifiedErrorId : ErrorInvalidParameter,Microsoft.Graph.PowerShell.Cmdlets.GetUserCalendarView_List

For this request, the query parameters are not part of a filter, so logic tells me not to use the -Filter parameter (?).

Docs for CalendarView

PS C:\WINDOWS\system32> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.18362.145
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.18362.145
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Specify certificate based authentication with cert thumbprint

Suggestion to support specifying the thumbprint of certificate to be used for certificate based authentication. This would be in addition to (or replacing) the option for certificate name. If I'm not mistaken the certificate name could be the same across many different certificates (like a display name) vs. the thumbprint which uniquely identifies the certificate (like an identifier).

Ex. Connect-Graph -ClientId "[clientId]" -TenantId "[tenantId]" -CertificateThumbprint "[certThumbprint]"

Update $GraphAuthConfigID with cumulative scopes

Currently $GraphAuthConfigID populates with only the most recently requested scopes during "Connect-Graph" connection. Recommend that during "Connect-Graph" execution to update the $GraphAuthConfigID variable with the cumulative set of scopes returned from the response.

Integrate dotnet SDK with powershell module

Powershell module generated by autorest has preconfigured httpclient. Plan is to investigate and understand the integration point and integrate dotnet SDK's core module and leverage httpclient with middleware capabilities in powershell modules.

Connect-graph: Value cannot be null, Parameter name: certificate

Hi
I'm testing out the msgraph-sdk-powershell and have installed the module. Using powershell 5.1.
I have Registered an App in my Azure and added a certificate that was created based on .\Create-SelfSignedCertificate.ps1 (https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azuread)

When trying to connect I get the following error:

Connect-Graph -ClientId $clientId -TenantId $TenantId -CertificateName "CN=MyCompanyName"

Connect-Graph : Value cannot be null.
Parameter name: certificate
At line:2 char:1
+ Connect-Graph -ClientId $clientId -TenantId $TenantId -CertificateNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-Graph], ArgumentNullException
    + FullyQualifiedErrorId : System.ArgumentNullException,Microsoft.Graph.PowerShell.Authentication.Cmdlets.ConnectGraph

I'm doing something wrong:s, but what?

Im able to get information via the app-registration using the
Invoke-RestMethod -Headers $Headers -Uri "https://graph.microsoft.com/v1.0/users/$UserPrincipalName/photo" -Method Get
Which means that the app registration and permissions are ok, perhaps I need to create a certificate another way?

Any tips are welcome!

brgs

BjΓΈrn

Generate powershell module using Autorest

Goal is to generate functional powershell module using openapi doc representation of graph apis. We need to document issues which fall in autorest domain vs apislice domain and fix issues which can be fixed by changes in apislice code.

PowerShell to get latest updates

If you installed the module when it was first released, like I did, you can use this PowerShell to get the latest version of the modules:

Set-PSRepository -Name GraphPowerShell -InstallationPolicy Trusted
Get-InstalledModule -Name "*graph*" | foreach { $b = (find-module $_.name).version ; if ($b -ne $_.version) { Write-host "Updating $($_.name) from $($_.version) to $b" } ; Update-Module -Name $_.name }

tk

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.