使用 PowerShell 监视共享文件夹的权限更改

时间:2021-04-30 15:06:50

标签: powershell automation acl servicenow fileserver

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

Shared folder which is used by others for accessing files

1 个答案:

答案 0 :(得分:1)

您可能正在寻找 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.'
}