gpt4 book ai didi

json - 通过 powershell 将消息发布到 MS Teams

转载 作者:行者123 更新时间:2023-12-03 00:55:33 35 4
gpt4 key购买 nike

这是我在这里发表的第一篇文章,希望我能得到一些帮助。我在 powershell 中创建了一个脚本,用于检查 azure 中服务主体的到期日期。脚本本身工作正常,但现在我想将脚本的输出发布到 MS Teams,而不是生成结果文件。这是一段代码。result.list 包含输出,我将其加载到 $Body

$Body = get-content -Path .\result.list

$JSONBody = [PSCustomObject][Ordered]@{
"@type" = "text/plain"
"@context" = "http://schema.org/extensions"
"summary" = "Incoming Alert Test Message!"
"themeColor" = '0078D7'
"title" = "Incoming Alert Test Message!"
"text" = "$Body"
}

$TeamMessageBody = ConvertTo-Json $JSONBody -Depth 100

$parameters = @{
"URI" = '<uri>'
"Body" = $TeamMessageBody
"ContentType" = 'application/json'
}

Invoke-RestMethod @parameters

这就是 result.list 的样子。例如,服务主体

DisplayName   : sp-acr-ldl-pull
ObjectId : ***********
ApplicationId : ***********
KeyId : ***********
Type : Password
StartDate : 6/23/2020 2:29:20 PM
EndDate : 6/23/2021 2:29:16 PM
Status : Expired

但在 Teams 中,它不是人类可读的,因为正文未正确传递

DisplayName: sp-acr-ldl-pull ObjectId: ********** ApplicationId : ********** KeyId: *********** Type: Password StartDate: 6/23/2020 2:29:20PM EndDate

如何格式化 $JSONBody 以在 Teams 中获得与 result.list 相同的相同输出?

最佳答案

基本上,问题是换行符,但您有两个相关的问题:

  1. 您正在使用 Get-Content 直接读取文件内容。默认情况下,在 PowerShell 中,这将返回的不是一个单个字符串,而是一个字符串数组,文件中的每一行对应一个项目。要将内容作为单个原始字符串获取,请添加 -Raw命令末尾的参数。

  2. 默认情况下,Teams 仅显示文本,不带任何格式(包括换行符)。如果要发送显式换行符,则需要告诉 Teams 这样做,并且可以使用 html“
    ”标签来执行此操作(Teams 消息正文支持 html 的有限子集)。为此,您可以替换 $body 中的换行符。 html 变量 <br>标签,像这样:$Body = $Body.Replace("`r`n", "<br>") .

请注意,您的 Invoke-RestMethod 上缺少“Method”参数命令。

这是最终的工作代码,包括上述内容:

$Body = get-content -Path "C:\temp\result.list" -Raw

$Body = $Body.Replace("`r`n", "<br>")

$JSONBody = [PSCustomObject][Ordered]@{
"@type" = "text/plain"
"@context" = "http://schema.org/extensions"
"summary" = "Incoming Alert Test Message!"
"themeColor" = '0078D7'
"title" = "Incoming Alert Test Message!"
"text" = "$Body"
}

$TeamMessageBody = ConvertTo-Json $JSONBody -Depth 100

$parameters = @{
"URI" = '<uri>'
"Body" = $TeamMessageBody
"ContentType" = 'application/json'
"Method" = "POST"
}

Invoke-RestMethod @parameters

所以这至少会给你换行符。如果您想保留“表格”样式格式,那么我建议使用自适应卡,也许类似于 FactSet 。您可以了解如何send Adaptive Cards在这里,这是一个 sample card using a FactSet ,但是您需要循环遍历这些行并构建 FactSet 和 Adaptive Card,因此希望早期的解决方案足够了。

关于json - 通过 powershell 将消息发布到 MS Teams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70084974/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com