Scheduled tasks don’t have any good way to be edited in Powershell, at least from what I have seen. The other day I set out to write some scripts to help me out. This isn’t really cleaned up or final (aka I haven’t figured out the best error checking yet and it could use a decent refactoring), but I figured I would go ahead and throw them up here to get some feedback.
function get-scheduledtask($server=$env:COMPUTERNAME)
{
$tempFile = $env:TEMP + "\scheduledtaskstemp.csv"
schtasks /query /S $server /FO csv /V | where { $_.length -gt 0 } | Set-Content $tempFile
Import-Csv $tempFile
Remove-Item $tempFile
}
function remove-scheduledtask($taskname, $server=$env:COMPUTERNAME, [switch]$verbose, [switch]$whatif=$variable:whatifpreference)
{
if(-not $taskname) { throw "Must provide taskname" }
$command = "schtasks /DELETE /TN '$taskName'"
if($server) { $command += " /S '$server' " }
if($verbose -or $whatif) { $command }
if(-not $whatif) { Invoke-Expression $command }
}
function run-scheduledtask($taskname, $server=$env:COMPUTERNAME, [switch]$verbose, [switch]$whatif=$variable:whatifpreference){
if(-not $taskname) { throw "Must provide taskname" }
$command = "schtasks /RUN /TN '$taskname'"
if($server) { $command += " /S '$server' " }
if($verbose -or $whatif) { $command }
if(-not $whatif) { Invoke-Expression $command }
}
function add-scheduledtask {
param
(
[string] $user,
[string] $password,
[string] $schedule,
[string] $runUser,
[string] $runPassword,
$modifier,
$days,
$idleTime,
$taskName,
$taskRun,
$startTime,
$months,
$startDate,
$endDate,
$server=$env:COMPUTERNAME,
[switch]$verbose,
[switch]$whatif = $variable:whatifpreference
)
if(-not $taskName) { throw "Must Provide a taskName" }
if(-not $taskRun) { throw "Must provide a taskRun" }
if(-not $schedule) { throw "Must provide a schedule" }
if(-not $runPassword) { throw "Must provide a runPassword" }
if(-not $runUser) { throw "Must provide a runUser"}
$command = "schtasks /CREATE /TN '$taskname' /TR '$taskRun' /SC '$schedule' /RU '$runUser' /RP '$runPassword' "
($user,"U"),
($password,"P"),
($modifer,"MO"),
($days,"D"),
($months,"M"),
($idleTime,"I"),
($startTime,"ST"),
($server,"S"),
($startDate,"SD"),
($endDate,"ED")|
%{
if($_[0]) { $command += " /$($_[1]) '$($_[0])' " }
}
if($verbose -or $whatif) { $command }
if(-not $whatif) { Invoke-Expression $command }
}