【问题标题】:Scripting - Watch changes for a file and send an email notification脚本 - 监视文件的更改并发送电子邮件通知
【发布时间】:2017-05-06 00:59:55
【问题描述】:

大家好,我是脚本新手。我正在尝试在文件更改时发送电子邮件通知。

我尝试使用下面的脚本只是为了在文件更改时收到通知,但是每次文件更改时我该怎么做。下面的脚本只工作一次,所以我把它放到一个无限循环中,以便在文件更改时注意到更改,但是,我知道这不是一个理想的方法。 我还需要发邮件。我怎么做。感谢您的回复。谢谢。

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
}

【问题讨论】:

    标签: windows powershell cmd scripting file-watcher


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-12-23
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多