Why it doesn’t work when PowerShell is run as administrator
If PowerShell is run in normal user mode, the whole script works fine and FileSystemWatcher works fine.
If PowerShell is run as administrator (right mouse button on icon and run as administrator) the whole script works fine, but FileSystemWatcher doesn’t execute the If’s it has in $action{}.
All the code that is in $action{} will work correctly anywhere else in the script and in $action{} it won’t. Why?
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = [System.IO.Path]::GetDirectoryName($path)
$watcher.Filter = [System.IO.Path]::GetFileName($path)
$watcher.NotifyFilter = [System.IO.NotifyFilters]::LastWrite #-bor [System.IO.NotifyFilters]::LastAccess
$watcher.EnableRaisingEvents = $true
$action = {
Block-FilePermissions -file_path $path
Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Write permissions blocked" -ForegroundColor Red
$global:pauseCycleCheck = $true
Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - pauseCycleCheck =
$pauseCycleCheck" -ForegroundColor Magenta
if ($selfModification -eq $true){
Unblock-FilePermissions -file_path $path
Write-Host "Allowed " -ForegroundColor Green
Set-Attributes
}
}
Register-ObjectEvent -InputObject $watcher -EventName "Changed" -Action $action