The following is a PowerShell Job Scheduling Script able to read a PowerShell script from a file and schedule it to run once, daily or weekly (while indicating which days of the week are selected). The script collects the options indicated by the user, assembles a commandlet, submits it to the user for review and executes it upon approval.
#How to register a Scheduled Job directly from Powershell
#If you do not run Powershell 3.0 please remove the -message parameter in the Get-credential command in the $scheduletask variable
Write-Host “`r`nSchedule An AppAssure Task Using Powershell`r`n——————————————-`r`n”
#default code location; make sure to add a semicolon at the end of each row.
$dfile = “c:\code.txt”
#Set New Job Name
$JobName = Read-Host “Choose a name for the Scheduled Job`r`nStart all Job Names with AppAssure i.e. Appassure Task 1;`r`nno quotation marks, please”
#Credentials for the Scheduled Job
# $cred = get-credential [will be performed at the time the task is scheduled]
$message = ‘ -message “Enter the User Name (domain\user) and Password under which the task will run”‘
#If you do not run Powershell 3.0 please remove the -message parameter in the $schedtask variable
#Get the code to be run
Write-Host “`r`nThe code to be executed will be read from a file;`r`nplease make sure that a semicolon is placed at the end of each row” -f “Yellow”
$file = Read-host “File with the powershell code [default $($dfile)]”
if (!($file)){$file = $dfile}
$script = get-content $file
#Try to put together the Trigger for the job
$JobInterval = Read-Host @”
`r`nSelect The Schedule Type
0. Once
1. Daily
2. Weekly
3. AtStartup
4. AtLogon
Enter the numeric value i.e. 1 for daily (no quotation marks, please)
“@
switch ($JobInterval)
{
0 { $param1 = ” -once “;
$param2 = Read-host “Enter the Date and Time [MM/dd/yyyy hh:mm AM/PM]”
$param2 = ” -at “”" + $param2 + “”" ”
$cmd = $param1 + $param2
break}
1 { $param1 = “-daily “;
$param2 = Read-host “Enter the Time [hh:mm AM/PM]”
$param2 = ” -at “”" + $param2 + “”" ”
$cmd = $param1 + $param2
break}
2 { $param1 = “-weekly “;
$param3 = read-host @”
Enter the days of the week
when the job is to be performed
i.e. Monday,Tuesday,Friday
“@
$param2 = Read-host “Enter the Time [hh:mm AM/PM]”
$param3 = “–DaysOfWeek ” + $param3
$param2 = “-at “”" + $param2 + “”" ”
$cmd = $param1 + $param2 + $param3
break}
3 { $param1 = “-AtStartup”
$cmd = ” ” + $param1 + ” ”
break}
4 { $param1 = “-AtLogOn”
$cmd = ” ” + $param1 + ” ”
break}
default {break}
}
$Schedulecmd = “Register-Scheduledjob -Name “”$jobname”" -credential (get-credential $message) -scriptblock { $script} -Trigger (New-JobTrigger $cmd) -ScheduledJobOption (New-Scheduledjoboption -RunElevated)”
$r = [scriptblock]::Create($Schedulecmd)
$validate = Read-Host @”
Are you sure that you want to schedule the following task?`r`n
$($r)
`r`n[Y/N]
“@
If ($validate.ToLower() -eq “y”) {
& $r
}
else {“Exiting…”}