FileSystemWatcher的执行.NET函数 [英] FileSystemWatcher to execute .NET functions
问题描述
我创建一个快捷临时的解决办法很抱歉,如果这是肮脏的,但─
I am creating a quick temporary fix so sorry if this is dirty, but-
目的
我想用Powershells注册-事件cmd以等待文件下降的文件夹中,然后调用一个函数,分析文件,并将其输出到Excel。我并不需要帮助与编码方案,只是概念。这仍然是一个有点神秘的对我作为此事件正在运行和它有什么一起工作。资源
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.
事情
-
一个名为.ps1文件底部注册的事件,要求在顶部,调用批处理文件的功能。
行为:的停止在这条线:
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)
这是.NET我的第一次调用,所以这就是为什么我是假设这是一个问题,.NET。
This is my first invocation of .NET, so this is why I was assuming it is an issue with .NET.
二的.ps1文件,FileWatcher和分析器,无论工作带来极大的单独运行时,调用批处理文件。
行为:的FileWatcher输出这行,但未能输出分析器任何线路,并且永远不会获取该行
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"
}
我甚是绝望去两个PS1文件和两个批处理文件。让我们只是说没有工作。
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
问题
为什么某些命令运行正常,从一个注册的事件调用时,等命令,像.NET不起作用?
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).
推荐答案
对我来说(code大多是从的这里):
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()
}
这篇关于FileSystemWatcher的执行.NET函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!