Run on a specific day only [PS snipets 01]

Today I decided to start a new series. In these, rather than rambleing about bigger projects, I just share some smaller scripts or script parts.

Here is one: I have been asked to figure out a way to run a certain task in the task scheduler, when the system reboots, but only on a certain day. Now by default, you can have either of these. A task executes either at startup or according to a time schedule. So what I came up with, is a script, that can be added to a task scheduler, scheduled with startup as the trigger. Then when it executes, it checks the day of the week (using Get-Date) and combines this with a simple if / else (really only the “if” part is needed) statement to only do the work, if it is matching. Using parameters it can be set o use other days too.

[cmdletbinding(SupportsShouldProcess = $True)]
[OutputType([int])]
param(
    [Parameter(Mandatory = $False)]
    [ValidateSet('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Satruday', 'Sunday')]
    [string]
    $thisday = 'Monday'
)
begin {
    $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
}
process {
    [DateTime]$today = Get-Date
    if ($today.DayOfWeek -match $thisDay) {
        Write-Host "It is $($today.DayOfWeek), so I will do this:" -ForegroundColor Green
        # ! put your code here for execution only on the day defined in the $thisday (default is Monday!)
        Write-Host 'Here we do some mega-awsome stuff!'
    }
    else {
        Write-Host "Relax, it is not $thisDay yet...it is $($today.DayOfWeek)..." -ForegroundColor Yellow
    }
}
end {
}

You can of course ommit the Write-Host parts – I just have them for the purpose of the demo. Also the “else” part is optional. Have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *

Close Bitnami banner
Bitnami