Automated .ps1 scripts with Task Scheduler

Action Options to run a script in Task Scheduler.

  • Program/Script: Scripts%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
  • Arguments: -File .\Copy-Jobs_SB.ps1
  • Start in(path): C:\Anaconda3\Notebooks\MyScriptsTEST

Schedule Setup

Pretty simple outline in the gui. Use the “run now” buttons to verify they will actually work though when ran on a schedule.

Use Secure Strings to at least hide the plain text passwords or keys you use in your scripts. Remember that you must generate a Secure String with the account you will be using.

Also make sure to automate these scripts from a secured server. No one should be able to easily connect and read these other than yourself of the security team.

Troubleshooting non-working scripts

Trouble Shooting a service account issue. For instance you originally used an account you tested with(like your personal user admin account etc)

Use a Try/Catch block in your ps1 script in the case you can’t tell if it’s something getting caught up while Task Scheduler runs the script. This happened to me when configuring a service account for production to run the script that I had originally tested with my user account. After verifying the script ran I found out it was getting caught up in the translation of a Secure String I created with my user account. These Secure Strings need to be generated by the account that runs the script.

Try {  

<DO SOMETHING>

}
#ASSIGN VARIABLES TO THE BUILT IN EXCEPTION RESULTS PRINT THEM TO A LOG
Catch {
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
$hrresult = $_.Exception.HResult
$stacktrace = $_.Exception.StackTrace
Add-Content c:\temp\log.txt "second error message was: $ErrorMessage Failed Item was: $FailedItem `nstacktrace was: $stacktrace $hrresult"
}





Below is an example of exceptions logged that deduced my issues to the Secure String used.

Future Improvements:

  • Run automated scripts using an MSA account