監視資料夾並刪除檔案(如果存在/建立)

監視資料夾並刪除檔案(如果存在/建立)

我想監視一個資料夾,每次創建特定名稱的檔案時,或者如果它只是存在,我想刪除它。我希望保留 Windows 7 的原生功能,以避免安裝其他軟體/軟體套件。我相信 Powershell 和 FileSystemWatcher 能夠做到這一點,但我對這兩者都沒有經驗。

具體的應用是,我的雇主定期(約90 分鐘)對我辦公室PC 上的資料夾“C:\Windows\System32\oobe\info\backgrounds”執行ping 操作,並添加“backgroundDefault.jpg”,並添加一些廣告。我想刪除此檔案以保留通用 Windows 預設檔。我嘗試創建一個名為“background1920x1080.jpg”的文件,因為我了解 Windows 會優先加載名稱中具有分辨率的文件,但似乎 1920x1080 不是這些公認的分辨率之一。

任何幫助深表感謝。

答案1

您可以使用檔案系統觀察器來監視檔案和資料夾並對其採取操作,這是很常見的事情,並在說明文件以及網路上的許多範例和預先建置腳本中顯示...

搜尋:“powershell 檔案系統觀察器”

檔案系統觀察者類 https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netframework-4.8

使用 PowerShell 追蹤資料夾的更改

$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher | Get-Member -Type Properties, Event 

$FileSystemWatcher.Path = "C:\Users\proxb\Desktop\DropBox"

Register-ObjectEvent -InputObject $FileSystemWatcher  -EventName Created  -Action {

    $Object = "{0} was  {1} at {2}" -f $Event.SourceEventArgs.FullPath,
    $Event.SourceEventArgs.ChangeType,
    $Event.TimeGenerated

    $WriteHostParams = @{
        ForegroundColor = 'Green'
        BackgroundColor = 'Black'
        Object          = $Object
    }
    Write-Host @WriteHostParams
} 

https://mcpmag.com/articles/2015/09/24/changes-to-a-folder-using-powershell.aspx

從 PowerShell 使用 FileSystemWatcher http://www.mobzystems.com/code/using-a-filesystemwatcher-from-powershell

....甚至有關該主題的視頻...

https://www.youtube.com/results?search_query=powershell+file+system+watcher

...以及已經在 MS TechNet 和 MS PowerShell Gallery 中...

Powershell 檔案系統觀察器

此腳本使用 .net FileSystemWatcher 類別訂閱 NTFS 檔案系統中檔案或資料夾的「建立」、「變更」和「刪除」事件。事件後採取的行動。

https://gallery.technet.microsoft.com/scriptcenter/Powershell-FileSystemWatche-dfd7084b/file/42206/1/FileSystemWatcher.ps1

……但與CMasMas先生所說的同上。不要在沒有計劃和通知的情況下隨意做出此類決定。

另外,這也顯示您總體上對 PowerShell 不熟悉

所以,你真的絕對需要先加強它,你的管子是你的朋友。切勿使用您不完全理解的方法進行破壞性行為。永遠不要隨機運行任何人的程式碼,無論是誰給你的或你從哪裡得到它,除非你完全理解使用它的後果。如果不小心,您可能會破壞您的系統和/或環境。

相關內容