大家好我是脚本新手。每当文件更改时,我都会尝试发送电子邮件通知。
我尝试使用下面的脚本只是为了在文件更改时收到通知,但是每次文件更改时我该怎么做。下面的脚本只工作一次,所以我把它放到一个无限循环中,以便在文件更改时注意到更改,但是,我知道这不是一个理想的方法。我还需要发邮件。我怎么做。感谢您的回复。谢谢你。
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
}