Author Posts

February 3, 2017 at 2:39 pm

Hi guys
A question: I got a script in that I can choose the wished day , clock and so one and this will be saved in this following script:
The aim is, that then powershell should create a scheduled Task with this script below, but it doesnt.

############################################################CODE###########################################################
$taskName = Read-Host "Name"
$user = "username"
$password = "username"
$action = New-ScheduledTaskAction -Execute "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-command path-to-powershell-script"

$trigger = {
if ($time -contains "daily") {
New-ScheduledTaskTrigger -Daily -AT $clock -DaysOfWeek $day
$settings = New-ScheduledTaskSettingsSet
$inputObject = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask -TaskName $taskName -InputObject $inputObject -User $user -Password $password }

elseif ($time -contains "weekly") {
New-ScheduledTaskTrigger -Weekly -AT $clock -DaysOfWeek $day
$settings = New-ScheduledTaskSettingsSet
$inputObject = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask -TaskName $taskName -InputObject $inputObject -User $user -Password $password }

elseif ($time -contains "monthly") {
New-ScheduledTaskTrigger -Monthly -AT $clock -DaysOfWeek $day
$settings = New-ScheduledTaskSettingsSet
$inputObject = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask -TaskName $taskName -InputObject $inputObject -User $user -Password $password
}
}

############################################################CODE###########################################################

I dont paste the another script because he is to big. Now my question:
What do i have to do , that my script (which you can see above) creates the schedule Task.
Is there a mistake or should I give you the main script for helping.

February 3, 2017 at 2:57 pm

It looks like all your New-ScheduledTaskTrigger/New-ScheduledTaskSettingsSet/New-ScheduledTaskTrigger/Register-ScheduledTask statements are wrapped in a script block which you assign to $trigger but don't invoke as far as I can see in what you've posted.

$trigger = {
if ($time -contains "daily") {
New-ScheduledTaskTrigger -Daily -AT $clock -DaysOfWeek $day
$settings = New-ScheduledTaskSettingsSet
$inputObject = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings
Register-ScheduledTask -TaskName $taskName -InputObject $inputObject -User $user -Password $password }
...
}

Additionally I don't see the $time variable being assigned anywhere in that script block which means neither of the if statements will evaluate to true.

I hope above makes sense.