Database Reference
In-Depth Information
When setting up the scheduled task the PowerShell.exe arguments were set as follows:
-NonInteractive -Command "& c:\Scripts\HighCommission.ps1 -outputPath
'C:\Dropbox\Report Outbox\' -commissionThreshold .3; exit $LASTEXITCODE"
The -NonInteractive argument is set since we won't be running the script in a user-
interactive way. The -Command argument is used instead of the -File argument since
we need to pass parameters to the script. We irst tell PowerShell to run the script
HighCommission.ps1 with "& c:\Scripts\HighCommission.ps1 . The outputPath
parameter for HighCommision.ps1 is then speciied, using single quotes since the directory
has a space in the path. Next the default .25 value for the script's commisionThreshold
parameter is overridden with a .3 value. Finally, a semicolon is used to separate a second
statement of exit $LASTEXITCODE , which is needed to kick any error exit code up the
chain, through PowerShell.exe's exit code, and onto the scheduled task result.
There's more...
You may notice the PowerShell command-line host popping up briely when running the
scheduled task. You may be able to avoid that by changing the user the scheduled task
runs under to NT AUTHORITY\SYSTEM . The user should be carefully considered in terms
of having enough permissions to perform the script actions but not more permissions than
necessary (as may be the case with SYSTEM ). Consider using a service account and use
caution when using an account where the password will eventually expire.
When developing a script to be run as a scheduled task and when modifying it, it's best to
run it within PowerShell irst, instead of from the scheduled task. If there are syntax or certain
other errors, you may not get any transcription output and any console that pops up may
disappear before you have time to see the error. If the script works from the console but
not from within the scheduled task, screen captures or screencasts can be used to snag any
temporarily visible error message. From there additional isolation changes can be made and
additional output writes added to help diagnose issues.
Another error tool is the built-in $Error variable. You can inspect $Error[0] to see the
most recent error or larger indexes to see prior ones. Finally you can query the $? automatic
variable; if it returns $false , the last command failed.
For scheduled tasks such as this one, sending an e-mail using System.Net.Mail.
SmtpClient can be useful. In this example in this recipe, attaching HighCommission.csv
on success and HighCommission.log on error would be a useful enhancement.
 
Search WWH ::




Custom Search