laitha0
laitha0

Reputation: 4336

FileSystemWatcher with PowerShell not working

I created a PowerShell script to monitor a folder for new files; it deletes files containing "cmr" and logs the names of the files that contains "cdr".

This all worked yesterday and today I decided to reboot and see if the event will stay but I can't even get it to work at all, I am not sure what happened.

$folder = "C:\Users\home\Documents\calldata"
$filter = '*.*'
Set-Location $folder
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

Register-ObjectEvent $fsw Created -SourceIdentifier NewCallData -Action{
    $name = $Event.SourceEventArgs.Name
    if($name -match "cmr"){
        Write-Host $folder\$name
        Remove-Item $folder\$name
    }
    if($name -match "cdr"){
        Out-File -FilePath C:\MCallPowershell\outlog.txt -Append -InputObject "$name"
    }
}

Upvotes: 1

Views: 947

Answers (1)

user2965349
user2965349

Reputation: 21

You might need to un-register your event to run a new instance:

Unregister-Event NewCallData

then run it again

Upvotes: 2

Related Questions