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
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.
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.
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
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.