FileSystemWatcher to execute .NET functions

余生长醉 提交于 2019-11-28 10:49:33

问题


I am creating a quick temporary fix so sorry if this is dirty, but-

Objective

I would like to use Powershells Register-Event cmd to wait for a file dropped in a folder, then call a function that parses the file and outputs it to excel. I don't need help with the coding aspect, just the concept. It is still a little mysterious to me as of where this Event is running and what resources it has to work with.

Things I've Tried

  1. One .ps1 file with registered events at the bottom, calling a function at the top, called by a batch file.
    Behavior: Stops on this line:

    $sr = new-object System.IO.StreamReader($copyPath)
    

    This is my first invocation of .NET, so this is why I was assuming it is an issue with .NET.

  2. Two .ps1 files, FileWatcher and Parser, both work great when run separately, called by a batch file.
    Behavior: FileWatcher Outputs "This Line" but fails to output any lines in Parser, and never gets to that line.

    Register-ObjectEvent $fsw Changed -SourceIdentifier FileChange -Action {
      Write-Host "This Line"
      .\src\Parser.ps1
      Write-host "That Line"
    }
    
  3. I even got as desperate as to go to two ps1 files and two batch files. Lets just say it didn't work.

Generic batch file command I am using:

powershell.exe -noexit C:\scripts\src\FileWatcher.ps1

Questions

Why does certain commands run fine when called from a registered event, and other commands like .NET not work?

Is what I am trying to achieve even possible?

Do you have a better way to achieve my objective? (Scripting only, remember this is a hotfix).


回答1:


The following worked for me (code mostly copied from here):

$folder = 'c:\Temp'
$filter = '*.*'

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

Register-ObjectEvent $monitor Created -SourceIdentifier FileCreated -Action {
  $name = $Event.SourceEventArgs.FullPath
  $sr = New-Object System.IO.StreamReader($name)
  Write-Host $sr.ReadToEnd()
  $sr.Close()
}


来源:https://stackoverflow.com/questions/17302652/filesystemwatcher-to-execute-net-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!