For this Quick PowerShell blog post, I will cover some quick examples of new code I have added to some of my more complicated scripts. The chunks of code are nearly standardized in three scripts I have created recently. They deal with some of the more benign aspects of PowerShell coding. I find them useful when I need to call on them. This list does not include all of these kinds of code blocks, but these are certainly useful:
Code Section One
For this section we are performing several actions – clearing the screen (to make the script process easier to follow), set a path for file output, setting a date variable and finally setting a buffer for the size of the PowerShell session to help capture wide output (last line):
CLS $Path = (Get-Item -Path ".\" -Verbose).FullName $Date = Get-Date -Format "MM.dd.yyyy-hh.mm-tt" $Host.UI.RawUI.BufferSize = New-Object Management.Automation.Host.Size (500, 9999)
Code Section Two
For this section of code, we set a file name and destination for a script log. Then we check to see if the log is present and if it is not, then set up a new file with a header:
$FileName = "LogFileName.txt" $Destination = $Path+"\"+$FileName $FileCheck = Test-Path $Destination If (-not($FileCheck)) { $Line = "Purpose of this Log File" | Out-File $Destination $Line = "------------------------" | Out-File $Destination -Append } Else { Write-host 'Transaction logging file exists!' }
After this section we can then log various things to this file to help troubleshoot or audit the actions post run of the script.
Code Section Three
For this section, we are utilizing a transcript file to keep track of what is run in the shell window for PowerShell. First we set a file name and destination. Then we try top stop and running Transcripts (which happens sometimes) and then start a new transcript process.
$TranscriptFile = "Transcript-"+"$Date"+".txt" $Transcript = $Path+"\"+$TranscriptFile # Stop any existing transcript Try { Stop-Transcript -ErrorAction SilentlyContinue } Catch { $Stop = $True } Try { Start-Transcript -Path $Transcript -NoClobber } Catch { Write-host 'No transcript is in progress.' -ForegroundColor Red}
End of the script:
Stop-Transcript -ErrorAction SilentlyContinue
This last line just closes off the Transcript file for the script.
Final Thoughts
Obviously the above code sections are not the only ones that could be standardized in your scripts. The function of the script should determine what goes into it. However, there are some items that can be put into all scripts to make them more useful. In the end, it is up to the script author to determine what should be present in their script.