top of page

A Good Ending

  • Writer: Damian Scoles
    Damian Scoles
  • Mar 4, 2019
  • 3 min read

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


Get-PSSession | Remove-PSSession


If you use this, ALL PowerShell sessions n 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:


$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$ExchangeServer/PowerShell/?SerializationLevel=Full" -Credential $OPCred -Authentication Kerberos -ErrorAction STOP

Import-Session $Session


Closing it with:


Exit-PSSession $Session



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:


Start-Transcript -Path "C:\FromOldLaptop\Temp\transcript.txt" -NoClobber


We could place a line like this to Stop an old transcript from a previous run and then start up a new transcript:


Try { Start-Transcript -Path "C:\FromOldLaptop\Temp\transcript.txt" -NoClobber -ErrorAction STOP } Catch { Stop-Transcript ; $Transcript = 'Stopped'}

If ($Trascript -eq 'Stopped') {

Start-Transcript -Path "C:\FromOldLaptop\Temp\transcript.txt" -NoClobber

}


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:


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


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:


Write-Host "Exiting..."


or something more involved like this could be used:


Write-Host ' '

Write-Host '--------------------------'

Write-Host ' End of the Script '

Write-Host '--------------------------'

Write-Host ' '


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:


$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

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.

 
 
 

Recent Posts

See All
Null. Empty. Space? How to Detect?

** Disclaimer ** I do not know everything about PowerShell and I am sure I will miss some methods of detection of empty values. However,...

 
 
 

Commenti


© 2016-2020 by Damian Scoles and Dave Stork.

bottom of page