首页 > 解决方案 > 使用 PowerShell 监控共享文件夹的权限更改

问题描述

我正在尝试编写一个脚本来监视共享文件夹权限的更改,但找不到任何东西。根据所附图片,如果有人尝试添加/删除任何组或用户或在此处更改权限,则应通知我用户详细信息和时间。欢迎您提出任何建议或参考。

其他人用来访问文件的共享文件夹

标签: powershellautomationaclservicenowfileserver

解决方案


您可能正在寻找FilesystemWatcher,但您需要进行这些代码更改以监控更改的安全性:

# specify the file or folder properties you want to monitor:
$AttributeFilter = [System.IO.NotifyFilters]::Security 

# specify the type of changes you want to monitor:
$ChangeTypes = [System.IO.WatcherChangeTypes]::Changed

请注意,此脚本必须始终运行以监视更改。可能无法监控远程共享。

编辑:这是从上面的链接中提取的一个最小示例,用于监视安全性或文件内容的更改。按照建议,我从异步版本开始捕获所有事件,而不仅仅是第一个:

try {
  $watcher = New-Object IO.FileSystemWatcher -Property @{
    Path = [Environment]::GetFolderPath('Desktop')
    Filter = '*'
    IncludeSubdirectories = $true
    NotifyFilter = @([IO.NotifyFilters]::Security, [IO.NotifyFilters]::LastWrite) #add any other notify filters to this array
    EnableRaisingEvents = $true
  }
  $handlers = .{#add any other events to listen for
    Register-ObjectEvent -InputObject $watcher -EventName 'Changed' -Action {Write-Host "`nChanged: $($event | ConvertTo-Json -Depth 5)"}
    Register-ObjectEvent -InputObject $watcher -EventName 'Deleted' -Action {Write-Host "`nDeleted: $($event | ConvertTo-Json -Depth 5)"}
  }
  Write-Warning "FileSystemWatcher is monitoring $($watcher.NotifyFilter) events for $($watcher.Path)"
  do{
    Wait-Event -Timeout 1
    Write-Host "." -NoNewline     # write a dot to indicate we are still monitoring:
  } while ($true)# the loop runs forever until you hit CTRL+C    
}finally{#release the watcher and free its memory
  $handlers | %{Unregister-Event -SourceIdentifier $_.Name }
  $handlers | Remove-Job
  $watcher.Dispose() 
  Write-Warning 'FileSystemWatcher removed.'
}

推荐阅读