4

PowerShell小技巧:通过Powershell 发送消息给企业微信机器人

 2 years ago
source link: https://blog.51cto.com/u_2877456/5335118
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

PowerShell小技巧:通过Powershell 发送消息给企业微信机器人

原创

在工作中经常会使用计划任务执行 Powershell 脚本,同时又需要基于执行的脚本及时反馈结果给相关人员。过去是通过 Powershell 发送邮件通知,但很多时候这类消息容易被忽略,没有及时沟通类的消息软件高效。

本篇以企业微信机器人为例,简单记录使用 Powershell 发送消息给企业微信机器人,便于后期集成在其他脚本中,以实现及时反馈运行结果的需求。如何创建机器人不在本文范围,请自行搜寻。

本文为 微风原创文章.经实践,测试,整理发布.如需转载请联系作者获得授权,并注明转载地址.


$Webhook = "https://qyapi.weixin.qq.com/xxx" # 这里填写机器人的Webhook 地址即可
Invoke-WebRequest $Webhook -Method POST -ContentType "application/json;charset=utf-8" -Body '{"msgtype": "text","text": {"content": "【测试企业微信机器人消息】"}}'

效果预览

watermark,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=
watermark,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=

这里有个简单的场景,默认计算机加域以后都会在Computers这个容器里,如果不移动至相应的 OU,则无法应用企业的相关GPO策略。我们可以定期执行脚本去检查 Computers 的计算机,如果有就通知相关人员进行移动。

脚本如下:

# Send message
$webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=*********"
$PClist = Get-ADComputer -SearchBase "CN=Computers,DC=ITPro,DC=cc"  -Filter 'Enabled -eq "True"' | Select-Object Name
$PCNames = $PClist.Name
$PCNumb = ($PClist.Name).count
$content = Write-Output "一共有"$PCNumb"台计算机加入域请尽快移动至相关OU,清单如下:`n "$PCNames""

$body = "{
    `"msgtype`":`"text`",
    `"text`":{
    `"content`":`"$content`",
    `"mentioned_list`":[`"jason`"]
    }
}"
$chinese = [System.Text.Encoding]::UTF8.GetBytes($body) #这里是解决中文编码问题的即发送中文消息时候使用。
if ($PCNumb -gt 0) {
    Invoke-RestMethod $webhook -ContentType "application/json" -Method Post  -Body $chinese
}
else {
    exit
}

执行结果:

watermark,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=

机器人消息也支持MarkDown格式,让输出的消息更加美观

watermark,size_14,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=

详细说明请见 官方文档

更多文章,欢迎订阅或访问我的个人博客:  Blog.ITPro.cc


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK