I am working on creating a task to setup a Task Scheduler job on Windows machine. I have a script that register Task scheduler, when I run the script from Terraform Customscript extension it is not giving any error or creating the schedule Task. Though I have tried to wright the stdout to a file, command is not giving any output after execution.
I have tried to run the same command on by login to machine and able to create task successfully.
Powershell command script name "TaskScheduler.ps1"
#Setup Task scheduler
echo "Settingup Schedule task" | Out-File -FilePath C:\Users\Script_output.log -Append
$taskTrigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Friday -At 8pm
$taskAction = New-ScheduledTaskAction -Execute "PowerShell" -Argument '-NoProfile -ExecutionPolicy Bypass -File "C:\Users\BackupScripts\backup.ps1"' -WorkingDirectory "C:\Users\BackupScripts"
From Terraform I am executing the command as follow :
powershell.exe -ExecutionPolicy Bypass -File C:/Users/BackupScripts/TaskScheduler.ps1
This method tends to offer more consistent results. Let me outline the basic concept, steps involved, and provide an example of PowerShell script logic to demonstrate how this approach can be effectively utilized.
Essentially, you'll need to copy the exported XML file of the Task Scheduler job to the target machine and then execute PowerShell on that machine for it to function correctly. If you can accomplish these steps in your environment, this approach should work seamlessly—that's the basic concept.
$TN = "My Task Scheduler Job XYZ";
If( !( Test-Path "C:\ProgramData\My Task Scheduler Job XYZ.xml" ) ){ Copy-Item "\\serverxyz\packages\SchedTasks\My Task Scheduler Job XYZ.xml" -Destination "C:\ProgramData" -Force; };
$job = Get-ScheduledTask | ForEach-Object { Process { If ( $_.TaskName -eq $TN ) { $_ } }};
If ( !$job ) { schtasks /CREATE /xml "C:\ProgramData\My Task Scheduler Job XYZ.xml" /TN $TN; };
If ( (Get-ScheduledTask | ? { $_.TaskName -eq $TN }).State -ne "Ready" ) { Enable-ScheduledTask -TaskName $TN };
Exit;