Skip to content

Instantly share code, notes, and snippets.

@EitanBlumin
Last active February 3, 2021 14:46
Show Gist options
  • Select an option

  • Save EitanBlumin/cd1f17d271c08c2010cbf411f51ea35d to your computer and use it in GitHub Desktop.

Select an option

Save EitanBlumin/cd1f17d271c08c2010cbf411f51ea35d to your computer and use it in GitHub Desktop.
Template Powershell script with built-in transcript log management
# when creating a scheduled task to run such scripts, use the following structure example:
# powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Madeira\Powershell_Template_with_Transcript.ps1"
Param
(
[string]$logFileFolderPath = "C:\Madeira\log",
[string]$logFilePrefix = "my_ps_script_",
[string]$logFileDateFormat = "yyyyMMdd_HHmmss",
[int]$logFileRetentionDays = 30
)
Process {
#region initialization
function Get-TimeStamp {
Param(
[switch]$NoWrap,
[switch]$Utc
)
$dt = Get-Date
if ($Utc -eq $true) {
$dt = $dt.ToUniversalTime()
}
$str = "{0:MM/dd/yy} {0:HH:mm:ss}" -f $dt
if ($NoWrap -ne $true) {
$str = "[$str]"
}
return $str
}
if ($logFileFolderPath -ne "")
{
if (!(Test-Path -PathType Container -Path $logFileFolderPath)) {
Write-Output "$(Get-TimeStamp) Creating directory $logFileFolderPath" | Out-Null
New-Item -ItemType Directory -Force -Path $logFileFolderPath | Out-Null
} else {
$DatetoDelete = $(Get-Date).AddDays(-$logFileRetentionDays)
Get-ChildItem $logFileFolderPath | Where-Object { $_.Name -like "*$logFilePrefix*" -and $_.LastWriteTime -lt $DatetoDelete } | Remove-Item | Out-Null
}
$logFilePath = $logFileFolderPath + "\$logFilePrefix" + (Get-Date -Format $logFileDateFormat) + ".LOG"
# attempt to start the transcript log, but don't fail the script if unsuccessful:
try
{
Start-Transcript -Path $logFilePath -Append
}
catch [Exception]
{
Write-Warning "$(Get-TimeStamp) Unable to start Transcript: $($_.Exception.Message)"
$logFileFolderPath = ""
}
}
#endregion initialization
#region install-modules
# replace the array below with any modules that your script depends on.
# you can remove this region if your script doesn't need importing any modules.
$modules = @("PSFramework", "PSModuleDevelopment", "dbatools")
foreach ($module in $modules) {
if (Get-Module -ListAvailable -Name $module) {
Write-Verbose "$(Get-TimeStamp) $module already installed"
}
else {
Write-Information "$(Get-TimeStamp) Installing $module"
Install-Module $module -Force -SkipPublisherCheck -Scope CurrentUser -ErrorAction Stop | Out-Null
Import-Module $module -Force -Scope Local | Out-Null
}
}
#endregion install-modules
#region main
# TODO: Replace this code with your actual script body:
Write-Output "$(Get-TimeStamp) Example output message. Check out the timestamp on this bad boy."
# When using Invoke-Sqlcmd, be sure to add parameters -OutputSqlErrors $true -Verbose to capture all output. For example:
Invoke-Sqlcmd -Server "." -Database "master" -Query "PRINT 'This is the output of a SQL command, generated by: ' + PROGRAM_NAME() + ' on server ' + @@SERVERNAME" -QueryTimeout 0 -OutputSqlErrors $true -Verbose
#endregion main
#region finalization
if ($logFileFolderPath -ne "") { Stop-Transcript }
#endregion finalization
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment