Why does FileSystemWatcher not work while PoweShell is run as Administrator?

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

Not a direct answer but maybe double check if the issue is because of the different user environment.
Since running as administrator is not the same user environment as currentuser.
E.g. is the path you’re using on the local machine or mapped, permissions, relative/absolute paths etc.

Again, just some thoughts.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.