Code to login and logout a user from Office 365

Occasional Visitor

Hi all,

First time here...


I am trying to write a code that will automatically logout the current Office 365 user from the account on the pc, and another option to login a certain user to Office 365.


I'm trying to do it in powershell, in which I do not have much experience, but I cannot find some matching code examples to start with.


Has anyone has such code to help me get started, please?

Other related ideas are mostly welcome


2 Replies

Hi Hanouch,


I would like to start answering your question with a question. :)  Why do you want/ this need this? Could you give some more context as of why you are creating a custom login/ logout procedure? Perhaps an alternate solution could help you better.


If a (your) workspace environment is setup correctly (using for example SSO) users are logged in automatically into Office 365, no code is necessary. 


But if you want to FORCE logout a certain user(s), the following might help you on your way:


  • Browser/ UI
    • In Office 365 Admin center, use the following the following steps.
      Office 365 Admin Center
      Users -> Active Users ->Select the User and in the OneDrive settings, click Initiate sign out
  • Powershell
    • Import-Module MSOnline
      $cred = Get-Credential
      Connect-MsolService -Credential $cred
      Connect-SPOService -Url <add you office365 SPO admin url here> -Credential $cred
      # To get all enabled users
      $users = Get-MsolUser -EnabledFilter EnabledOnly -All
      # To get all the users
      #$users = Get-MsolUser;
      foreach ( $user in $users){
          Revoke-SPOUserSession -user $user.UserPrincipalName -Confirm:$false


The user(s) that you FORCE logout can immediately log back in unless you have blocked their account. Also when using the Powershell option you need to be Global admin.


Hope this helps and I'm looking forward in reading some more context as of why you would want to write such a script. 

The PS commands you gave above are for an admin to force logout of multiple people. Can you furnish commands that would allow me to log myself out only?


The use case is this: if I log in at 9am on Monday, it logs me out automatically one day later. If I'm in a Teams meeting at that time, it forces me to exit the meeting, which can be very disruptive. To avoid that disruption I need to remember to log out and re-log in before the meeting. I would far prefer to be logged out automatically at a fixed time every day, say 5am, so when I start work I am forced to log in immediately and then don't have to worry about it for the remainder of the day.


I know that my IT department could do this, but they've got bigger fish to fry at the moment, so I need this script.