Forum Discussion

Joe McNicholas's avatar
Joe McNicholas
Brass Contributor
Apr 13, 2017
Solved

O365 Script - credentials prompt

Hi All

 

I have long running scripts running against O365 for our tenant. These can take a day or two to complete.  During the run of the script, there can be an interuption where the credentials manager popup requests the credentials again, despite me having entered them at the beginning of the script.

 

I can't find a way to handle this programatically so that the creds are returned and the script continues.

 

Can anyone help?

 

Here's the code for the connection at the start of the script:

Import-Module MSOnline
$O365Cred = Get-Credential
$O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred -Authentication Basic -AllowRedirection
Import-PSSession $O365Session
Connect-MsolService –Credential $O365Cred

5 Replies

  • Gorazd Nadižar's avatar
    Gorazd Nadižar
    Copper Contributor

    Hello,

     

    I'm using this one and works great for me : 

     

    Set-ExecutionPolicy RemoteSigned
    $UserCredential = Get-Credential
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
    Import-PSSession $Session

     

     

     

     

     

    • Joe McNicholas's avatar
      Joe McNicholas
      Brass Contributor

      Thanks Gorazd - that's about the same as what I use. My problem is that after a few hours the O365 session goes into a broken state and the script stops.

       

      I've added some logic to remove the O365 session and re-connect to O365 every 15 mins to avoid this problem, and it looks promising. I have a script that has now been running for about 18 hours without stopping....

  • That's just a side effect of broken session to Exchange Online and PowerShell's attempt to recconect to it. The best thing you can do is to optimize your script to run as efficiently as possible, using server-side filtering and Invoke-Command in order to reduce the execution time. Apart from that, you can include a check for the session state before running each cmdlet/iteration. An example of such script can be found here: https://gallery.technet.microsoft.com/scriptcenter/Start-RobustCloudCommand-69fb349e

     

    There are some other recommenadations you can find here: https://blogs.technet.microsoft.com/exchange/2015/11/02/running-powershell-cmdlets-for-large-numbers-of-users-in-office-365/

    • Joe McNicholas's avatar
      Joe McNicholas
      Brass Contributor

      Thanks for the information, I'll look into using these techniques.  Shame there's no simple "silver bullet" here..... :(

Resources