Not sure if anyone is as clumsy as me and manages to have a failing powershell script for over four months before noticing it, but better safe than sorry, so here is a quick and easy way to self-test your scripts.
(Disclaimer: I can’t really say that I understand the intricacies of what I’m doing, so use at your own risk and please feel free to post improvements.)
So, what’s the problem? - If you use scripts to run your duplicacy backups, there is a risk that you make some (often minor) edits, not realizing that you actually just broke your script, i.e. your backup won’t run. Windows Task Scheduler won’t tell you, and if you don’t have a more sophisticated #monitoring mechanism in place, chances are, you won’t notice until it’s too late.
Quick and easy solution: Add the following code to the beginning of your backup script and make sure to adust the paths accordingly. (I just couldn’t be bothered to code this more elegently.)
What does it do? Every time the script runs, it checks itself for any syntax errors. If it doesn’t find any, it writes an empty file with a file-name indicating that all is OK. If it finds an error, it deletes that file and writes another file instead.
function Syntax-OK
{
[CmdletBinding(DefaultParameterSetName='File')]
param(
[Parameter(Mandatory=$true, ParameterSetName='File')]
[string]$Path,
[Parameter(Mandatory=$true, ParameterSetName='String')]
[string]$Code
)
$Errors = @()
if($PSCmdlet.ParameterSetName -eq 'String'){
[void][System.Management.Automation.Language.Parser]::ParseInput($Code,[ref]$null,[ref]$Errors)
} else {
[void][System.Management.Automation.Language.Parser]::ParseFile($Path,[ref]$null,[ref]$Errors)
}
return [bool]($Errors.Count -lt 1)
}
if(Syntax-OK -Path C:\duplicacy\scripts\backup_alpha_C.ps1){
New-Item -Path 'C:\duplicacy\scripts\backup_alpha_C.ps1-STATUS_OK' -ItemType File
Remove-Item –Path 'C:\duplicacy\scripts\backup_alpha_C.ps1-STATUS_ERROR-please_check_script'
}else {
New-Item -Path 'C:\duplicacy\scripts\backup_alpha_C.ps1-STATUS_ERROR-please_check_script' -ItemType File
Remove-Item –Path 'C:\duplicacy\scripts\backup_alpha_C.ps1-STATUS_OK'
}
Source: validation - How can I automatically syntax check a powershell script file? - Stack Overflow
This is obviously the most basic version of the script possible. Feel free to improve it.