jblz
jblz

Reputation: 1029

Scheduled task created via powershell, to run powershell code generating Error Value: 2147942667

I want to run the following powershell code as a scheduled task, also deployed via powershell.

$postParams = @{hostname=hostname;key="keyhere"}; Invoke-WebRequest -Uri https://url.com/url -Method POST -Body $postParams

I'm using the following code to create a Windows scheduled task that should run the code.

$repeat = (New-TimeSpan -Minutes 5)
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' `-Argument '-NoProfile -WindowStyle Hidden -command "& {$postParams = @{hostname=hostname;key="keyhere"}; Invoke-WebRequest -Uri https://url.com/url -Method POST -Body $postParams}"'

$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval $repeat

Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Update IP" -Description "IP update"

While this successfully creates the task itself, running this provides the following error in the task history, and does not execute the code

Task Scheduler failed to launch action "Powershell.exe" in instance "{9b40f292-92cc-47dc-9041-d3b2d266d82b}" of task "\Update IP". Additional Data: Error Value: 2147942667.

Searching this error online typically suggests its a quote issue when specifying paths and I can't find much else on the subject.

I'd like to avoid running this from it's own .ps1 file if possible, and to get it work in the above manner (due to the way this is being deployed).

Can anyone assist please?

Upvotes: 0

Views: 555

Answers (1)

Vad
Vad

Reputation: 743

you have an extra back tick ( "`" ) before the -Argument parameter due to which the task does not receive arguments, it's must be like this:

$repeat = (New-TimeSpan -Minutes 5)
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "& {$postParams = @{hostname=hostname;key="keyhere"}; Invoke-WebRequest -Uri https://url.com/url -Method POST -Body $postParams}"'

$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).Date -RepetitionInterval $repeat

Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Update IP" -Description "IP update"

Upvotes: 1

Related Questions