0

I have a script that runs fine from within Powershell, but it will not work correctly when triggered from Task Scheduler or a Powershell Scheduled Job.

Here is the script (this is a boiled-down version of the script found here):

$folder = 'D:\<folder_to_monitor>'
$filter = '*.*'
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Swithmail /s /x "c:\swithmail\msg_send.xml"}

I can run this script in Powershell, then execute a Get-EventSubscriber command and I'll see the result:

SubscriptionId   : 2
SourceObject     : System.IO.FileSystemWatcher
EventName        : Created
SourceIdentifier : FileCreated
Action           : System.Management.Automation.PSEventJob
HandlerDelegate  : 
SupportEvent     : False
ForwardEvent     : False

I can then drop new files into the folder being monitored and I'll receive an email, as designed. Wonderful! Works like a champ.

Now I want to run this script on startup so that I don't have to remember to run it every time the server is rebooted. I set up the task in Task Scheduler, following these directions. I then manually start the task (don't want to reboot the server during production), but after doing so, when I run the Get-EventSubscriber command I get nothing. Dropping files into the monitored folder does not send the email.

I also tried setting up a scheduled job by following these directions (I set up the job to trigger at a set time for testing, not with the -AtStartup variable), but still the event doesn't seem to be registering like it does when I run the script outright.

EDIT 1: Per suggestions from @BiNZGi and @Nick, I checked Event Viewer and there were no entries there related to this the Task Scheduler task or the script. So, also as suggested, I added lines to the script to start and stop the PS transcription feature:

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path C:\batch\scriptlog.txt -append

$folder = 'D:\<folder_to_monitor>'
$filter = '*.*'

$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Swithmail /s /x "c:\swithmail\msg_send.xml"}

Stop-Transcript

Results: the scriptlog.txt file is being created, and it appears that the "FileCreated" event is being registered:

**********************
Windows PowerShell transcript start
Start time: 20191119112406
Username: <mydomain>\administrator
RunAs User: <mydomain>\administrator
Machine: <myserver> (Microsoft Windows NT 6.3.9600.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File c:\batch\<myscript>.ps1
Process ID: 8984
**********************
Transcript started, output file is C:\batch\scriptlog.txt
Id     Name            PSJobTypeName   State         HasMoreData     Location
--     ----            -------------   -----         -----------     --------
1      FileCreated                     NotStarted    False
**********************
Windows PowerShell transcript end
End time: 20191119112407
**********************

However, creating a new file in the monitored folder doesn't generate the email, making me think the registered event still isn't working. Yet, when I run the script from within Powershell ISE it works fine. I get the same output when I type the Get-EventSubscriber command in Powershell ISE as I see in the scriptlog.txt file.

I wonder if the event registration doesn't like to be called from within a Task Scheduler task? From what I can read in the Help page, it's session-based. Perhaps Powershell doesn't recognize the Task Scheduler task as a session....?

Stumpage continues. :-/

HSVScott
  • 1
  • 1
  • I think there is something wrong with the permission or the configuration of the scheduled task. In first step check Windows Event Viewer (Win+R `eventvwr.msc`) > Windows Logs > Application and System. If there is nothing suspicious try to write Logs of the output of the PowerShell script using `Start-Transcript`, see https://stackoverflow.com/a/1215395/4772880 – BiNZGi Nov 19 '19 at 08:59
  • When this has happened to me, it's usually because the account running the script has to be logged into the server. I set the server to automatically log in as the account on reboot and that usually fixes it. While most of mine run through task scheduler, I also have scripts in the startup folder on the server which check the logged in username and start if it's the correct service account - again leveraging auto-login. But I agree with @BiNZGi, add some logging and make sure the script is starting, see where it fails, etc. – Nick Nov 19 '19 at 14:02
  • Thanks, y'all. I'll start digging. – HSVScott Nov 19 '19 at 16:30
  • Also, thank you to @Rich Moss for catching my mistake of using "Task Manager" instead of "Task Scheduler." Whoops! I was a little frustrated when I typed my question. ;-) – HSVScott Nov 19 '19 at 16:36
  • Okay, nothing in Event Viewer. I mean, nothing at all. No entries with the same timestamp as the moment I start the Task Scheduler task that kicks off the script. – HSVScott Nov 19 '19 at 17:50

0 Answers0