是否有任何選項可以在發生特定事件(即插入閃存驅動器)時運行任務,但每月只執行一次?
我正在嘗試將我的備份腳本掛接到某些自動事件。
作業系統:Windows 7 x64 專業版
答案1
您有使用 WMI 的經驗嗎(Windows 管理工具)?它非常適合此類任務。此外,它是 Windows 的一部分,因此它應該導致最小的開銷。
以下是 Perl 腳本的範例,該腳本在插入 USB 隨身碟時執行一些簡單的操作。
一些變數
use Win32::OLE::Const 'Microsoft WMI Scripting';
my $ComputerName = "localhost";
my $NameSpace = "root/cimv2";
my $WbemServices = Win32::OLE->GetObject("winmgmts://$ComputerName/$NameSpace");
註冊事件(USB 插入)
my $Instance = $WbemServices->Get(__EventFilter)->SpawnInstance_();
$Instance->{Name} = "myfilter";
$Instance->{QueryLanguage} = "WQL";
$Instance->{Query} = qq[SELECT * FROM __InstanceCreationEvent WITHIN 1
WHERE TargetInstance ISA 'Win32_LogicalDisk'
and TargetInstance.Name<>'B:'
and TargetInstance.Name<>'A:'];
# there are other queries possible
my $Filter = $Instance->Put_(wbemFlagUseAmendedQualifiers);
my $Filterpath = $Filter->{path};
定義行動
# example 1 : execute script
my $Instance = $WbemServices->Get(ActiveScriptEventConsumer)->SpawnInstance_();
$Instance->{Name} = "myscript";
$Instance->{ScriptingEngine} = "PerlScript";
$Instance->{ScriptText} = q[open FILE, ">>C:\\\\usb.txt";print FILE "USB plugged in\n";];
# you could call your backup script / check for dates / etc.
# example 2 : execute command
my $Instance = $WbemServices->Get(CommandLineEventConsumer)->SpawnInstance_();
$Instance->{Name} = "mycommand";
$Instance->{CommandLineTemplate} = "echo Hello world!";
# you could call your backup script / check for dates / etc.
my $Consumer = $Instance->Put_(wbemFlagUseAmendedQualifiers);
my $Consumerpath = $Consumer->{path};
連結事件和動作
my $Instance = $WbemServices->Get(__FilterToConsumerBinding)->SpawnInstance_();
$Instance->{Filter} = $Filterpath;
$Instance->{Consumer} = $Consumerpath;
my $Result = $Instance->Put_(wbemFlagUseAmendedQualifiers);
這是永久活動註冊的一種形式。若要停用並清理整個過程,請刪除已建立的物件:
- __EventFilter 實例“myfilter”
- __EventConsumer 實例“myscript”或“mycommand”
- __EventToConsumerBinding 實例
您可以使用 WMI CIM Studio 搜尋物件。可從 Microsoft 免費下載,這裡。
答案2
有腳本:
檢查檔案 (/etc/last_backup) 是否存在且時間少於 X 天。否則不進行備份(因為這樣做不值得:不到 30 天前發生了另一次備份)
如果不存在,或早於 X 天,則進行備份。一旦備份 100% 完成,它就會觸及該檔案(觸及 /etc/last_backup)。
這樣您還可以知道上次完整備份發生的時間(查看 /etc/last_backup)
有一種方法可以知道文件是否存在並且時間少於 30 天:
find /etc -mtime -30 | grep /etc/last_backup >/dev/null 2>/dev/null
緊接著,$?如果 grep 可以找到它,則為“0”
這樣,要強制備份,只需刪除 /etc/last_backup 文件,下次腳本就會開始備份。
答案3
我建議任務規劃程序會是一個更簡單的想法。然而,成功取決於找到事件的觸發器,為此我會查看事件日誌。
我的想法是掌握備份命令,保存在腳本中,然後使用任務計劃程序服務的強大功能來處理定時。