Code Monkey home page Code Monkey logo

exch-rest's Introduction

Exch-Rest Getting Started Guide

The Exch-Rest module is a PowerShell module for the Office 365 and Exchange 2016 REST API that allows you to access the functionality provided by the Graph API ** New ** To jump to the How Can I one-liner QandA samples see this (Make sure you have connected to the mailbox first before running)

Setup

Module installation

The Module is available from the PowerShell Gallery at https://www.powershellgallery.com/packages/Exch-Rest and can be installed on Windows, Azure Cloud Shell or Linux where Power Shell Core has been installed

    Install-Module Exch-Rest

    Import-Module Exch-Rest

Or you can use the following steps to download and install the module from the GitHub repo

    # Set constants
$SourceCodeURL = "https://codeload.github.com/gscales/Exch-Rest/zip/master"
$UserModuleHome = "~\Documents\WindowsPowerShell\Modules"

# Download a zip of the source code
Invoke-WebRequest -Uri $SourceCodeURL -OutFile "~\Exch-Rest-master.zip"

# Unblock the downloaded file
Unblock-File "~\Exch-Rest-master.zip"

# Extract the zip
Expand-Archive "~\Exch-Rest-master.zip" -DestinationPath $UserModuleHome

# Remove "-master" from the name
Move-Item "$UserModuleHome\Exch-Rest-master" "$UserModuleHome\Exch-Rest"

# Delete the downloaded source code
Remove-Item "~\Exch-Rest-master.zip"

# Import the module
Import-Module -Name Exch-Rest

Connecting and Authenticating

To connect to a Mailbox which will start the authentication process that will allow you to then use the cmdlets defined in the module use the following

Windows

Connect-EXRMailbox -MailboxName [email protected]

Linux and Azure Cloud Shell

$Cred = Get-Credential -UserName [email protected]
Connect-EXRMailbox -MailboxName mailbox@domain -Credential $Cred

Authentication Options

Using the ADAL Authentication Library

By Default the Module uses its own Native Script based oAuth Authentication scripts however to support a greater range of Authentication scenarios the ADAL library is also distributed with the Module and available for use

To use the ADAL libraries for Logon use the following

connect-exrmailbox -MailboxName [email protected] -useADAL

To use the Never Prompt to use the ADAL Cache

connect-exrmailbox -MailboxName [email protected] -useADAL -Prompt Never

For connecting using the currently logged on credentials use

connect-exrmailbox -MailboxName [email protected] -useADAL -useLoggedOnCredentials -AADUserName [email protected]

(The -AADUserName variable is optional but usually required read the GitHub link in the second bullet point)

Certificate Authentication - If you wish to use App Only token using certificate based Authentication then see the certificate Authentication document

Application registration

The Office 365 / Exchange 2016 REST API uses OAuth 2.0 to authenticate users. This means that people using an application that use this API do not need to give you their username/password. Instead, they authenticate against a central authentication system (e.g. Azure AD, Active Directory) and you get back a token which is then passed to the API endpoint for authentication. You can then give your application permission to use that token to do a limited number of things for a specific period of time.

However, to use OAuth tokens you must register an application in Azure before you can use the Exch-Rest functions.

You have two options when it comes to doing this, the most secure option is to register your own Application and assign just the permissions (or Permission Grants) you want the Module cmdlets to have based on what data you want to access using the module. The other option is to use one of the default Application registrations that have been registed for use in a Tenant that is owned by the module's Author Glen Scales. If no ClientId is specified when using Connect-EXRMailbox a menu will be presented with the different Application Registration options and the permissions they will need. eg

If you select one of these Id's the first time you run this in a Tenant it will prompt for administrative consent for the permissions that the cmdlet will need to access the Mailbox Items (or OneDrive, Directory,Report etc) eg you should see a screen similar to

If you want to create your own Application registration and permission grants (which is recommended) there is a good walk through of the application registration process is provided by Jason Johnston at https://github.com/jasonjoh/office365-azure-guides/blob/master/RegisterAnAppInAzure.md.

The following is an overview of the steps you can take to create an application registration:

  • Browse to http://dev.office.com/app-registration and login into your Azure tenant
    • Click + New application registration, fill out the options, and click Create
      • Name: <Name-of-app-users-will-see>
      • Application type: Native
      • Sign-on URL: http://localhost
    • Click your newly created application and note the Application ID. You will need this later as your Client ID.
    • Click Redirect URIs, you should see http://localhost. Replace that entry with urn:ietf:wg:oauth:2.0:oob
    • Click Required permissions and then click + Add
    • Click 1 Select an API, click Office 365 Exchange Online (Microsoft.Exchange), and then click Select
    • Check off all the permissions that you wish to use, and then click Select. (Note: there seems to be a bug with the CheckAll button so you may have to individually check off each permission)
    • Click Done

Once you have done this you can set the Id you created to be the default Application registration everytime you use Connect-EXRMailbox (saving your from needing to enter it again). To do this select the Number 5 Option from the below menu

It will the prompt you to enter the clientId that was created when you registered the application and the redirectURI (generally this will be urn:ietf:wg:oauth:2.0:oob if you have used a native app) eg

Once the default Application has been set the console menu will no longer show when you use the Connect-EXRMailbox cmdlet. If you want to show the menu again, just add the -ShowMenu switch eg

Connect-EXRMailbox -Mailbox [email protected] -ShowMenu

Using the Module

Once you have succesfully authenticated and your token has been cached locally you can start using the cmdlets defined in the module.

How Can I Examples

Because this module has a large number of cmldets to help simplify every day tasks to make the documentation more useful I've created a How Can I page which simple lists a one word question and one/two line example taking into account that you have authenticated with a Application registration that has sufficient rights. see How Can I examples

The -MailboxName parameter

Most cmdlets have a -MailboxName switch which will control which mailbox a cmdlet is run against eg let's look an example

In the above example No MailboxName is used so the Mailbox that was used in the orginal Connect-EXRMailbox cmd will be used. This is because that MailboxName is cached in the AccessToken.

If you want to connect to a particular Mailbox you should use the -MailboxName parameter as follows

Cmdlets that don't connect to a specific Mailbox don't need the Mailboxname passed in eg like Get-EXRUsers which will retrieve all the user objects in the Azure Directory eg

Other Useful Examples

Show the last email from the Focused Inbox

Get-EXRLastInboxEmail -MailboxName [email protected] -Focused

Show the last email from the Other (Focused Inbox)

Get-EXRLastInboxEmail -MailboxName [email protected] -Other

Exporting the Contacts Folder of a Mailbox to CSV

To Export the contacts in a user's Contacts folder you can use the Export-EXRContactFolderToCSV cmdlet

Export-EXRContactFolderToCSV -mailboxname [email protected] -FileName c:\temp\MailboxContacts.csv

Showing the Meeting Rooms in your Tenant

Find-EXRRooms

Create a new user created folder in a Mailbox's Inbox Folder

New-EXRFolder -MailboxName [email protected] -ParentFolderPath '\Inbox' -DisplayName "My New Folder for Processing"

Show the Folder Retention Tags applied to a folder

Get-EXRFolderFromPath -MailboxName [email protected] -FolderPath \Inbox -PropList (Get-EXRItemRetentionTags)

Reporting

The Microsoft graph API provides access to the Office 365 usage reports for tenants and the module allows access to these reports eg getting the Mailbox Sizes and usage for the last 7 days

To vary the report duration you can pass in a different duration in the -PeriodType parameter eg to use 30 days instead of the default 7 use

exch-rest's People

Contributors

greiginsydney avatar gscales avatar yuriysamorodov avatar

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

exch-rest's Issues

Inbox rule support

I am interested in working on adding functions to create/read/update/delete inbox rules. I'll plan to work on that soon.

Comment Based Help (CBH)

The Exch-Rest module lacks CBH for most (if not all?) commands, lacking example usages. Please add CBH to each command.

Two onedrive folders

There is a onedrive folder at Exch-Rest/functions/onedrive/ which appears to have been updated 3 years ago.

There is another onedrive folder at Exch-Rest/functions/other/onedrive/ which appears to have been updated 2 years ago.

It seems that they hold the same functions, though I haven't checked yet if the functions in the folders differ in their code.

Poshlook cli client

Have you checked my project, if you to contribute let me know. It's a pine like mail client in powershell and .net

Performing admin activities with single token

I'm sure I'm just missing something, but I've written a script to grab all users and pull their mailbox rules. The rule works fine against my account, but when I try to run against other mailboxes it tells me I don't have an access token.

I have the app registered, granted app permissions, created a self-signed cert, updated the manifest and used the cert and cert pw to connect to my mailbox.

Here's part of my script so you can see what I'm trying to do:

Connect-EXRMailbox -MailboxName '[email protected]' -certificateFileName C:\temp\cert.pfx -clientId xxxx-xxxx-xxxx-xxxx -certificateFilePassword $password -ResourceURL graph.microsoft.com

#get enabled users
$users = get-exrusers -filter 'userType eq ''member'' and accountEnabled eq true'

$forwardAbuseRules = @()

#loop through users
foreach ($user in $users){
   #get mailbox rules
    $mbxRules = Get-EXRInboxRule -MailboxName $user.userPrincipalName
    #loop through rules and add to RuleObj if "forwardTo" is a property of actions
    foreach ($rule in $mbxRules){
        If ($rule.actions | get-member forwardTo){
            $RuleObj = [PSCustomObject]@{
                UserName = $user.displayName
                UserUPN = $user.userPrincipalName
                RuleName = $rule.displayName
                RuleID = $rule.id
                RuleEnabled = $rule.isEnabled
                RuleAction = 'forwardTo'
                RuleConditions = $rule.conditions
                ForwardAddress = $rule.actions.forwardTo.emailAddress.address
                Domain = $rule.actions.forwardTo.emailAddress.address.split("@")[1]
                }
            
            $forwardAbuseRules += $ruleObj
            $ruleObj = $null
        }```


Here's what I get when I try to run against other mailboxes:
```Get-EXRAccessToken : No Access Token for [email protected]
At line:49 char:20
+ ...           $AccessToken = Get-EXRAccessToken -MailboxName $MailboxName
+                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-EXRAccessToken

Get-EndPoint : Cannot bind argument to parameter 'AccessToken' because it is null.
At line:57 char:48
+         $EndPoint =  Get-EndPoint -AccessToken $AccessToken -Segment  ...
+                                                ~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-EndPoint], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Get-EndPoint

App Token has expired
At line:124 char:25
+                         throw "App Token has expired"
+                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (App Token has expired:String) [], RuntimeException
    + FullyQualifiedErrorId : App Token has expired```

License?

Very cool library, Glen! Can you add a license file so we can know how we could use your code?

Authentication with Certificate error

Hi I am connecting to a mailbox using:

PS C:\> Connect-EXRMailbox -MailboxName [email protected] -certificateFileName "C:\temp\cert.cer" -clientId "c637e71c-ceb1-4dde-8e3a-
xxxxxxxxx"

When it prompts me for password, I get this:

PS C:\> Connect-EXRMailbox -MailboxName [email protected] -certificateFileName "C:\temp\cert.cer" -clientId "c637e71c-ceb1-4dde-8e3a-
xxxxxxxxx"
Enter password for certificate file: ***********
Exception calling "CreateSignature" with "1" argument(s): "No asymmetric key object has been associated with this formatter object."
At line:68 char:3
+         $sig = [System.Convert]::ToBase64String($sigform.CreateSignat ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : CryptographicUnexpectedOperationException

Cached Token for graph.microsoft.com xxxxxxxxxxxx.onmicrosoft.com
Error getting Access Token
At line:144 char:21
+                     throw "Error getting Access Token"
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (Error getting Access Token:String) [], RuntimeException
    + FullyQualifiedErrorId : Error getting Access Token

Any Idea why the built in module is not converting the password correctly?

Improve documenation

Thanks for doing this Glen. If it's OK, I plan to open issues as a way to discuss changes I'd like to propose and get your input before I start working on something. As a bit of a warm up and a way to familiarize myself with all the work you've done, I'd like to work on improving the documentation.

Token Refresh is not working

if you work very long with one Token, the Module tries to update the Token but ultimatly fails :

connected to mailbox
Refreshed Token ADAL
Add-Member : Das Argument kann nicht an den Parameter "InputObject" gebunden werden, da es NULL ist.
In Zeile:103 Zeichen:57

  • ... Add-Member -InputObject $token -NotePr ...

Problems installing

I have tried installing via this method Install-Module Exch-Rest Import-Module Exch-Rest and get the error message

PS C:\windows\system32> Install-Module Exch-Rest Import-Module Exch-Rest
Install-Module : A positional parameter cannot be found that accepts argument 'Import-Module'.
At line:1 char:1

  • Install-Module Exch-Rest Import-Module Exch-Rest
  •   + CategoryInfo          : InvalidArgument: (:) [Install-Module], ParameterBindingException
      + FullyQualifiedErrorId : PositionalParameterNotFound,Install-Module
    
    
    
    

I then tried using the script and get this error

Import-Module : The module manifest 'C:\Users\g051700\Documents\WindowsPowerShell\Modules\Exch-Rest\Exch-Rest.psd1' could not be processed because it is not a valid
Windows PowerShell restricted language file. Remove the elements that are not permitted by the restricted language:
At C:\Users\g051700\Documents\WindowsPowerShell\Modules\Exch-Rest\Exch-Rest.psd1:22 char:9

  • GUID = 'fa6095ab-c4b8-4919-ae37-d09d00d23bb3'
  •     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    

Unexpected token 'fa6095ab-c4b8-4919-ae37-d09d00d23bb3'

Author of this module

Author = 'Glen' in expression or statement.
At C:\Users\g051700\Documents\WindowsPowerShell\Modules\Exch-Rest\Exch-Rest.psd1:22 char:9

  • GUID = 'fa6095ab-c4b8-4919-ae37-d09d00d23bb3'
  •     ~
    

The hash literal was incomplete.
At C:\Users\g051700\Documents\WindowsPowerShell\Modules\Exch-Rest\Exch-Rest.psd1:123 char:1

  • }
  • ~
    Unexpected token '}' in expression or statement.
    At line:21 char:1
  • Import-Module -Name Exch-Rest
  •   + CategoryInfo          : ResourceUnavailable: (C:\Users\g05170...\Exch-Rest.psd1:String) [Import-Module], MissingMemberException
      + FullyQualifiedErrorId : Modules_InvalidManifest,Microsoft.PowerShell.Commands.ImportModuleCommand
    
    

I have launched the ISE as Administrator. I am running Windows 10 on PS version PSVersion 5.1.14393.1770

Any help / suggestions would be greatly appreciated.

Thanks!

Id must be non-empty error when running New-EXRContact

Getting the below error message when trying to add a new contact into use mailbox.

This is the command i used and got the below error:
New-EXRContact -MailboxName [email protected] -FirstName "FirstName" -LastName "Surname of Contact" -EmailAddress "[email protected]" -MobilePhone 1111-222-333

{"error":{"code":"ErrorInvalidIdEmpty","message":"Id must be non-empty."}}

This is the requestURL that i get which i can see contactFolders is empty? not sure if this is the cause.
https://graph.microsoft.com/v1.0/users('[email protected]')/contactFolders('')/Contacts/

Thanks

Get-EXREMailAppUsageAppsUserCounts

Hi,

Really loving this module,

However, I'm having some trouble running the cmdlet in the title.

I'm able to get a token that is using an App in Azure and my admin mailbox but whenever I run the cmdlet i get this error.

Is this something I am doing wrong?

PS C:\windows\system32> Get-EXREmailAppUsageAppsUserCounts | FT
https://graph.microsoft.com/v1.0/reports/getEmailAppUsageAppsUserCounts(period='D7')?$format=text/csv

Error making REST Get :
RequestURL : https://graph.microsoft.com/v1.0/reports/getEmailAppUsageAppsUserCounts(period='D7')?$format=text/csv
You cannot call a method on a null-valued expression.
At line:25 char:9

  •     $OutPutStream = $Output.ReadAsStreamAsync().Result
    
  •     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidOperation: (:) [], RuntimeException
    • FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At line:26 char:16

  • ... return ConvertFrom-Csv ([System.Text.Encoding]::UTF8.GetString($ ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidOperation: (:) [], RuntimeException
    • FullyQualifiedErrorId : InvokeMethodOnNull

Applying retention policy to folder:

Applying a retentionpolicy to folder with this command:
Set-EXRFolderRetentionTag -RetentionFlagsValue 137 -retentionperiodvalue 0 -PolicyTagValue '414C6A14-3ED5-432E-9EDB-C6620A8278F0' -FolderPath '\inbox\Retention Folder'

Leaves me this error:
{"error":{"code":"RequestBodyRead","message":"The property 'PropertyId' does not exist on type
'microsoft.graph.singleValueLegacyExtendedProperty'. Make sure to only use property names that are defined by the type or mark the type as open type."}}

No matter what folder I run it on. I obtained the policytagvalue by running this command:
get-EXRFolderfrompath -MailboxName $mailbox.userprincipalname -FolderPath '\inbox\Retention Folder' -PropList (Get-EXRItemRetentionTags)

amd then converted the value it returned in base64 into the full GUID.

Question: onPrem Exchange

This is really just a question:
How can I connect to an on premise Exchange 2016, using username and password?

Authenticate without user interaction

Hello,
I'm willing to download attachments, which I've found the guidelines on your blog but I don't find a way to automate it without user interaction.
Could you give me some guidelines about how to achieve this ?
I've already tried with appid and appsecret but it keeps asking for credentials anyways. Is there a way to pass credentials into Powershell as it would be okay for me ?

Thank you !

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.