Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

powershell - FileSystemWatcher to execute .NET functions

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"
      .srcParser.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:scriptssrcFileWatcher.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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...