New-PSSscheduledTask.ps1


<#PSScriptInfo

.VERSION 0.1

.GUID 03c6be99-8437-4c8a-825b-647efcab2e1f

.AUTHOR Adam Bertram

.DESCRIPTION
    A script to execute a PowerShell script on a remote computer.

.COMPANYNAME Adam the Automator, LLC

#>


<#
    .SYNOPSIS
        This script creates a PowerShell script on a remote computer and schedules that script to be executed by a
        Windows scheduled task.

    .EXAMPLE
        PS> .\New-PSSscheduledTask.ps1 -ComputerName FOO -Name BAR -ScriptBlock { Write-Host 'Boo' } -Interval Daily -Time '12:00'

        This example creates a PowerShell script on the remote computer FOO with the content of "Write-Host 'Boo'". It then
        creates a scheduled task named BAR that is triggered every day at 12PM running under the highest privilege as
        SYSTEM.

#>

[OutputType([void])]
[CmdletBinding()]
param
(
    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [string]$ComputerName,

    [Parameter(Mandatory)]
    [string]$Name,

    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [scriptblock]$Scriptblock,

    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [ValidateSet('Daily', 'Weekly', 'Once')] ## This can be other intervals but we're limiting to just these for now
    [string]$Interval,

    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [string]$Time,

    [Parameter()]
    [ValidateNotNullOrEmpty()]
    [ValidateSet('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')]
    [string]$DayOfWeek,

    [Parameter()]
    [ValidateNotNullOrEmpty()]
    [pscredential]$RunAsCredential
)

$createStartSb = {
    param($taskName, $command, $interval, $time, $taskUser)

    ## Create the PowerShell script which the scheduled task will execute
    $scheduledTaskScriptFolder = 'C:\ScheduledTaskScripts'
    if (-not (Test-Path -Path $scheduledTaskScriptFolder -PathType Container)) {
        $null = New-Item -Path $scheduledTaskScriptFolder -ItemType Directory
    }
    $scriptPath = "$scheduledTaskScriptFolder\$taskName.ps1"
    Set-Content -Path $scriptPath -Value $command

    ## Create the scheduled task
    schtasks /create /SC $interval /ST $time /TN `"$taskName`" /TR "powershell.exe -NonInteractive -NoProfile -File `"$scriptPath`"" /F /RU $taskUser /RL HIGHEST
        
}

$icmParams = @{
    ComputerName = $ComputerName
    ScriptBlock  = $createStartSb
    ArgumentList = $Name, $Scriptblock.ToString(), $Interval, $Time
}
if ($PSBoundParameters.ContainsKey('RunAsCredential')) {
    $icmParams.ArgumentList += $RunAsCredential.UserName    
} else {
    $icmParams.ArgumentList += 'SYSTEM'
}
    
Invoke-Command @icmParams