I am totally new to Powershell, but I needed an all-Windows solution for a Slack bot that monitors local folders.
I am able to use the CLI to post to Slack successfully with the following two commands:
$postSlackMessage = @{token="";channel="#general";text="Test message";username="Bot User"}
Invoke-RestMethod -Uri https://slack.com/api/chat.postMessage -Body $postSlackMessage
I am also able to monitor the folder using the script provided on this superuser answer by @nixda.
My version of this great solution doesn't seem to cut it. Here it is:
### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "C:\Location\"
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true
### DEFINE ACTIONS AFTER A EVENT IS DETECTED
$action = { $path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
$token = ""
$channel = "$general"
$text = "$changeType, $path"
$username = "Bot User"
$postSlackMessage = @{token=$token; channel=$channel; text=$text; username=$username}
Invoke-RestMethod -Uri https://slack.com/api/chat.postMessage -Body $postSlackMessage
}
### DECIDE WHICH EVENTS SHOULD BE WATCHED + SET CHECK FREQUENCY
$created = Register-ObjectEvent $watcher "Created" -Action $action
$changed = Register-ObjectEvent $watcher "Changed" -Action $action
$deleted = Register-ObjectEvent $watcher "Deleted" -Action $action
$renamed = Register-ObjectEvent $watcher "Renamed" -Action $action
while ($true) {sleep 5}
I've tried a number of different variations on this and I am not sure what I'm doing wrong. I can get the nixda script to work and write to a txt file but changing the action to Invoke-RestMethod doesn't work.
Is this a syntax problem I'm not getting, or something greater I'm missing?