脚本 - 观察文件的更改并发送电子邮件通知

时间:2016-12-20 18:04:33

标签: windows powershell cmd scripting file-watcher

大家好我不熟悉脚本。我试图在文件发生变化时发送电子邮件通知。

我尝试使用以下脚本来获取通知,如果文件已更改,但每次文件更改时我该怎么做。下面的脚本只工作一次,所以我把它放到一个无限循环中,以便在文件被更改时注意到变化,但是,我知道它不是理想的方法。 我还需要发一封电子邮件。我怎么做。感谢您的回复。谢谢。

while (1 -eq 1)
{$File = "C:\Test\test.log"
$Action = 'Write-Output "The watched file was changed"'
$global:FileChanged = $false

function Wait-FileChange {
    param(
        [string]$File,
        [string]$Action
    )
    $FilePath = Split-Path $File -Parent
    $FileName = Split-Path $File -Leaf
    $ScriptBlock = [scriptblock]::Create($Action)


    $Watcher = New-Object IO.FileSystemWatcher $FilePath, $FileName -Property @{ 
        IncludeSubdirectories = $false
        EnableRaisingEvents = $true
    }
    $onChange = Register-ObjectEvent $Watcher Changed -Action {$global:FileChanged = $true}

    while ($global:FileChanged -eq $false){
        Start-Sleep -Milliseconds 100
    }

    & $ScriptBlock 
    Unregister-Event -SubscriptionId $onChange.Id
}

Wait-FileChange -File $File -Action $Action
}

1 个答案:

答案 0 :(得分:1)

脚本本身不必为了触发事件而保持运行,它们在powershell主机中注册,并将一直监视您的文件,直到该控制台关闭。所以如果你打开一个PowerShell窗口并运行下面的东西(显然你需要定义你的变量等等),那么下面实际上会工作,然后只是让控制台打开(这样做作为后台任务变得有点棘手)

$Watcher = New-Object IO.FileSystemWatcher $FilePath, $FileName -Property @{ 
    IncludeSubdirectories = $false
    EnableRaisingEvents = $true
}
Register-ObjectEvent $Watcher Changed -Action $Action
相关问题