Powershell Reports running Through Schedule Tasks Fails due to Remote powershell connection breaks in between.

Creating a new session for implicit Remoting of “Get-Mailbox” Command….

I have couple of powershell reports running for Exchange Online (office 365) for one of my client, these reports fetches data from multiple cmd lets, some reports takes hours to complete and in between if the powershell session breaks then report breaks too, to handle this situation I did the following.

When powershell connection with remote host is broken then powershell module file .Psm1 is designed to reconnect to remote host from the same session and prompts for password, which is good for the interactive session but when you are running script in scheduled task the session will be non-interactive, in that situation your login fails, which will cause script to fail.

To overcome this situation we need to change the code Microsoft put in place to prompt for password in the .psm1 module file.

So how we start ..

1st thing it will be a bad idea if we modify the temp module for the login as this will be replaced by the new module as soon as we run Import-PsSession command so here rather than importing module we will export it.

So let’s say I want to connect to Exchange online (Office 365)

# Set the path below for the Module file

$path= “$home\Documents\PowerShellModules”

Now Connect to Office 365 by running below command

$Cred = Get-Credential

$s=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $cred -Authentication Basic –AllowRedirection

Once connected, let’s now Export the module and Cmds start with Get-

Run below command to exported the exchange module and cmds offline.

Export-PsSession -session $s  -commandname get-*  -outputModule “$path\Exchange” -encoding ASCII

Note: if you wants to update the existing cmds, you run the above command with the –force switch

Now once the download is finished you be able to see the below File in the Exchange Folder.

Exchange.psd1

Exchange.Psm1

Exchange.format.ps1.xml

Now we will edit the module file Exchange.psm1.

Open the file using notepad, Scroll down to below condition in the script module file and remove red highlighted code and replicated with green.

Note: you can save a back copy of the file to reedit.

if (($script:PSSession -eq $null) -or ($script:PSSession.Runspace.RunspaceStateInfo.State -ne 'Opened'))

    { Write-PSImplicitRemotingMessage ('Creating a new session for implicit remoting of "{0}" command...' -f $commandName)

  Set-PSImplicitRemotingSession  -CreatedByModule $true         

-PSSession ( $ ( & $script:NewPSSession ` -connectionUri 'https://pod51041psh.outlook.com/powershell-liveid?PSVersion=3.0 ' -ConfigurationName 'Microsoft.Exchange'  -SessionOption (Get-PSImplicitRemotingSessionOption) 

-Credential ( $host.UI.PromptForCredential( 'Windows PowerShell Credential Request', 'Enter your credentials for https://pod51041psh.outlook.com/powershell-liveid?PSVersion=3.0 .', 'pod51041psh.outlook.com' ) )  -Authentication Basic -AllowRedirection ) )

-Credential  $cred -Authentication Basic  -AllowRedirection  ) )

Note: $cred is an array we have defined above.

There are various different ways to store password for script automation if you wants to check please through me blog here for the same.

Now save the file, open a new PowerShell session and load the module

You can load saved module by running the below command

Import-Module Exchange

Load the credential in the session

$cred = Get-credential

Once credential loaded in $cred Array you are ready to run the command from the console and you will not be promoted for the password and Powershell session will automatically connect with remote server and will display the results.

That is end of the document here, I hope you like my blog.

Top of Form

 

Comments

  1. HOLY GRAIL

    I've tried storing credentials, and I created a Refresh-PsSession script, but it only works about 90% of the time. In the event the session breaks between Refresh-PsSession and the CMDLET running against Exchange, the prompt comes up and my nightly process hangs, and valuable time is wasted. You have no idea how valuable this is...I owe you a beer sir. kudos ☺

    ReplyDelete
  2. I dub this the Holy Grail of automation. Thanks so much for posting this!

    ReplyDelete
  3. Thanks, This was a huge help.

    ReplyDelete
  4. Is it possible to do something similar to this in the new Exchange Online Powershell Module when using Connect-EXOPSSession with MFA?

    ReplyDelete
    Replies
    1. the MFA powershell module is not exportable, and required the UI prompot for the multi fector auth to work but you can try the replacing the like 140 in the module saved in "%temp%" folder

      -Credential ( $host.UI.PromptForCredential( 'Windows PowerShell Credential Request', 'Enter your credentials for https://outlook.office365.com/PowerShell-LiveId?BasicAuthToOAuthConversion=true.', 'admin@domain.onmicrosoft.com', 'outlook.office365.com' ) )
      with
      -Credential $credential # $credential must be your $Global:credential array saved with your admin credentials.

      Delete

Post a Comment