Powershell:无法使用其他可正常工作的脚本发布到 Slack

Powershell:无法使用其他可正常工作的脚本发布到 Slack

我对 Powershell 完全陌生,但我需要一个全 Windows 解决方案来监控本地文件夹的 Slack 机器人。

我可以使用 CLI 通过以下两个命令成功发布到 Slack:

$postSlackMessage = @{token="";channel="#general";text="Test message";username="Bot User"}

Invoke-RestMethod -Uri https://slack.com/api/chat.postMessage -Body $postSlackMessage

我还可以使用提供的脚本来监视文件夹这个超级用户的回答来自@nixda。

我这个解决方案似乎不太适用。如下所示:

### 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}

我尝试了多种不同的方法,但不确定我做错了什么。我可以让 nixda 脚本运行并写入 txt 文件,但将操作更改为 Invoke-RestMethod 不起作用。

这是我没有意识到的语法问题,还是我忽略了更重要的东西?

答案1

由于对此有少数看法,我将发布更正后的脚本,正如 Techie007 指出的那样。这只是一个小拼写错误,如果您想使用 Powershell 脚本在 Windows 中监视文件夹,请将此发布到 Slack:

### 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}

相关内容