A Good Ending

Like all good scripts, starting off well should be reciprocated with a good ending as well. What does that mean? Think processing, cleanup, ending transcripts, truncating log files and more. So how can we do this? What types of cleanup can be accomplished at the end of a script run. Keep in mind that these are not requirements, but they are good suggestions. Let’s take a quick peak at several closeout options for ending a PowerShell script:

Like all good scripts, starting off well should be reciprocated with a good ending as well. What does that mean? Think processing, cleanup, ending transcripts, truncating log files and more. So how can we do this? What types of cleanup can be accomplished at the end of a script run. Keep in mind that these are not requirements, but they are good suggestions. Let’s take a quick peak at several closeout options for ending a PowerShell script:

PowerShell Session Cleanup

It is very common to end up leaving loose ends when it comes to PowerShell connection sessions. Cleaning these up can help alleviate a few issues. These issues include commands that are cached from a previous session, memory used as well as clearing up sessions to Office 365 so as to not run into the three session limit for those connections. How can we remove these sessions?
[sourcecode language=”powershell”]
Get-PSSession | Remove-PSSession
[/sourcecode]
If you use this, ALL PowerShell sessions in the current shell will be closed. If there is a desire to be more careful, then you would have to write code to keep track of your session, or use the $Session variable to connect and end a session:
[sourcecode language=”powershell”]
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$ExchangeServer/PowerShell/?SerializationLevel=Full" -Credential $OPCred -Authentication Kerberos -ErrorAction STOP
Import-Session $Session
[/sourcecode]
Closing it with:
[sourcecode language=”powershell”]
Exit-PSSession $Session
[/sourcecode]
Ending Your Transcript
If you use Transcripts with your PowerShell scripts, make sure to add this to the end of you script:
Stop-Transcript
Additionally, if you want to make for a cleaner start, you can check to see if a transcript is in progress end it and restart a new one. Let’s say your script always uses this line for starting it’s transcript process:
[sourcecode language=”powershell”]
Start-Transcript -Path "C:\FromOldLaptop\Temp\transcript.txt" -NoClobber
[/sourcecode]
We could place a line like this to Stop an old transcript from a previous run and then start up a new transcript:
[sourcecode language=”powershell”]
Try { Start-Transcript -Path "C:\FromOldLaptop\Temp\transcript.txt" -NoClobber -ErrorAction STOP } Catch { Stop-Transcript ; $Transcript = 'Stopped'}
If ($Transcript -eq 'Stopped') {
Start-Transcript -Path "C:\FromOldLaptop\Temp\transcript.txt" -NoClobber
}
[/sourcecode]
Ending Log files

Similar to the transcript files above, when a script is ending, there may be some logging that needs to end in a different manner. It’s also possible your log files don’t need a cap, say if the log files are dated (date and time) to the point where all log files are unique. However, if there is a mast log file that is kept, it could be capped in the beginning and end like this:
[sourcecode language=”powershell”]
Beginning:
$Line = ' ' | Out-File $Destination -Append
$Line = "### START @ $Date ###" | Out-File $Destination -Append
$Line = ' ' | Out-File $Destination -Append
End:
$Line = ' ' | Out-File $Destination -Append
$Line = "### END @ $Date ###" | Out-File $Destination -Append
$Line = ' ' | Out-File $Destination -Append
[/sourcecode]
These lines provide a definite ending and beginning to a PowerShell script’s log files.

Interactive – Visual

When an interactive script ends, it might be nice to put some lines of code at the end to let people know that it is exiting. Something as simple as this may be ok:
[sourcecode language=”powershell”]
Write-Host "Exiting…"
[/sourcecode]
or something more involved like this could be used:
[sourcecode language=”powershell”]
Write-Host ' '
Write-Host '————————–'
Write-Host ' End of the Script '
Write-Host '————————–'
Write-Host ' '
[/sourcecode]
Removing files

This is a topic we have covered before, but it is worth re-reading here –> https://www.practicalpowershell.com/blog/powershell-cleanup-tips

Sending Email

Sending an email could be the logical end to a script that makes changes, queries changes or is monitoring an environment. There are a lot of ways to do this, but the simplest looks something like this:
[sourcecode language=”powershell”]
$Subject = "AD Remediation Changes Made – Test Email"
$To = 'damian@practicalpowershell.com'
$From = 'noreply@practicalpowershell.com'
$SMTPServer = 'mx.practicalpowershell.com'
$Body = 'Reports are attached.'
Send-MailMessage -To $To -From $From -Subject $Subject -Body $Body -SMTPServer $SMTPServer
[/sourcecode]
From the above, we see that we have these data points – Sender, recipients, subject, body, server. Additionally we can specify attachments as well.

Conclusion

As you can see from the above examples, there are many things that could potentially be done at the end of a PowerShell script to close it out. When planning a script, know what the intended purpose will be, whether there are files to clean up, log files to end, emails to send out and if its interactive and needs a visual end as well. Just remember to start out with your prerequisites and end with closing out any of those prerequisites that need closing or an end.

Related Post