PowerShell:FileSystemWatcher 不工作

PowerShell: FileSystemWatcher not working

代码运行没有错误,但是当我 add/delete 文件系统中的文件时,代码没有执行它在 Register-ObjectEvent $watcher "watchType" -Action $action 中应该执行的操作。我知道这一点是因为在过去,它正在工作并且会 create/add 到 log.txt 文件 deleted/added 及其日期的记录。现在,什么也没有发生。怎么回事?

代码:

#local path of the folder you want to sync. By default sets to current directory
$localPath = get-location

#filter specific files by name/type
$filter = "*.*"


#include subdirectories
$inclSubDirectories = $true


#end of user defined variables

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $localPath
$watcher.Filter = $filter
$watcher.IncludeSubdirectories = $inclSubDirectories
$watcher.EnableRaisingEvents = $true
$oldContent = ""

$action = {
    $path = $Event.SourceEventArgs.FullPath
    $changeType = $Event.SourceEventArgs.ChangeType

    $logline = "$(Get-Date), $changeType, $path"
    Add-content "'$localPath'\log.txt" -value $logline
}

$created = Register-ObjectEvent $watcher "Created" -Action $action

$action1 = {
    $path = $Event.SourceEventArgs.FullPath
    $changeType = $Event.SourceEventArgs.ChangeType
    $logline = "$(Get-Date), $changeType, $path"
    Add-content "'$localPath'\log.txt" -value $logline
}

$deleted = Register-ObjectEvent $watcher "Deleted" -Action $action1

$exitAction = {
    "File wathcer unregistered!"
    Unregister-Event $created
    Unregister-Event $deleted
}

$exit = Register-EngineEvent PowerShell.Exiting -action $exitAction

while ($true) {
    if($oldContent -eq $logline){}
    else{
        $logline
        $oldContent = $logline
    }
    Start-Sleep -m 1000
}

编辑

我决定尝试将代码直接复制并粘贴到 PowerShell 中,它按应有的方式工作... 不完全是,它不输出但它确实更新 log.txt 就像它应该的那样。 实际上,它只工作了一次。现在又回到了以前的样子。

编辑 v2

当我复制粘贴到 PowerShell 时,每个事件(创建,然后删除)似乎只工作一次(例如,它会注册一个在日志中删除的文件,然后它会注册一个创建的文件,但是它不会做任何其他事情。)它仍然没有像它应该的那样输出。

我可以在这里看到你的 $localpath 有当前路径,当你这样做时问题就来了 Add-Content

在下一行中,路径中带有单引号,无论如何都不存在。

Add-content "'$localPath'\log.txt" -value $logline

只需打印 "'$localPath'\log.txt".

即可查看

正确的表达方式是Add-content "$localPath\log.txt" -value $logline

以及每次 Register-ObjectEvent 执行时,都会创建一个作业,请尝试

Receive-Job -Id <Job ID> -keep看看什么是happening/happened.

此致

kvprasoon