如何使用 Windows 批处理检测文件更改?

问题描述 投票:0回答:1

我想监控特定文件。每次有变化我都想得到通知。
在 Linux 中,有一个完美的小程序可以完成该任务,称为

monit
。不幸的是我在 Windows 中没有这样的工具:-(

我四处寻找 Windows 内置的文件监控程序 - 但找不到任何东西。有一些比较文件的工具,例如

fc
find
,您可以在其中“查看”文件内部。但他们并没有真正帮助我。

是否可以使用批处理文件来监视文件更改而无需安装额外的软件?

batch-file comparison file-monitoring
1个回答
0
投票

DetectFileChange.bat

@echo off
REM DetectFileChange.bat
REM Michael Hutter / Februar 2024

if "%1"=="" goto Syntax
if "%2"=="" goto Syntax
if not exist "%1" goto Syntax

set "originalFile=%1"
set "copyFile=%2"

rem Überprüfen, ob die Kopie existiert
if not exist "%copyFile%" (
    echo Kopie der Datei existiert nicht. Erstelle eine neue Kopie...
    copy "%originalFile%" "%copyFile%"
)

rem Auslesen der Zeitstempel
for %%A in ("%originalFile%") do set "originalTimeStamp=%%~tA"
for %%B in ("%copyFile%") do set "copyTimeStamp=%%~tB"

rem Vergleichen der Zeitstempel
if "%originalTimeStamp%" neq "%copyTimeStamp%" (
    echo Die Datei wurde geändert!
    call :TheFileWasChanged %originalFile% %copyFile% "%originalTimeStamp%" "%copyTimeStamp%" TempAlertFile
    copy /Y "%originalFile%" "%copyFile%"
    del %TempAlertFile%
) else (
    echo Die Datei wurde nicht geändert. %originalTimeStamp% gleich %copyTimeStamp%
)
echo Ende
exit /b

:Syntax
echo Detect file changes (by file timestamp)
echo Syntax:
echo   %0 FileToMonitor CopyOfMonitoredFile
echo   %0 C:\FileToMonitor.txt C:\Temp\CopyOfMonitoredFile.txt
exit /b

:TheFileWasChanged
setlocal enableDelayedExpansion
set sChangeAlertFile=C:\Temp\ChangeAlert.txt
set sFileNameNow=%1
set sFileNameBefore=%2
set sTimestampNow=%3
set sTimestampBefore=%4
echo The file !sFileNameNow! has changed: (!sTimestampBefore! to !sTimestampNow!) > !sChangeAlertFile!
echo. >> !sChangeAlertFile!
echo New Content: >> !sChangeAlertFile!
echo ============ >> !sChangeAlertFile!
type !sFileNameNow! >> !sChangeAlertFile!
for %%a in (1 2) do echo. >> !sChangeAlertFile!
echo Old Content: >> !sChangeAlertFile!
echo ============ >> !sChangeAlertFile!
type !sFileNameBefore! >> !sChangeAlertFile!
start notepad !sChangeAlertFile!
timeout /t 2 > nul
(endlocal & set %5=%sChangeAlertFile%)
goto :eof
© www.soinside.com 2019 - 2024. All rights reserved.