Public/PSTeam.ps1
enum MessageType { Alert Cancel Disable Download Minus Check Add None } function Optimize-JSONString { [CmdletBinding()] param( $str ) if ($str -eq $null) {return ""} $str = $str.ToString().Replace('"', '\"').Replace('\', '\\').Replace("`n", '\n\n').Replace("`r", '').Replace("`t", '\t') return $str } function Get-Image { [CmdletBinding()] param( [string] $ImagePath ) return [convert]::ToBase64String((Get-Content $ImagePath -Encoding byte)) } function Send-TeamsMessage { [CmdletBinding()] Param ( [Parameter(Mandatory = $true)][MessageType]$MessageType, [Parameter(Mandatory = $true)][string]$messageTitle, [Parameter(Mandatory = $true, ParameterSetName = 'SetBody')][string]$messageBody, [Parameter(Mandatory = $true, ParameterSetName = 'SetSummary')][string]$messageSummary, [string]$activityTitle, [string]$activitySubtitle, [array]$details = $null, [string]$detailTitle, [array]$buttons = $null, [Parameter(Mandatory = $true)][string]$URI, [bool] $Supress = $true ) [bool] $UseImage = $false if ($MessageType -eq [MessageType]::None) { } else { $PathToImages = "$($($(Get-Module -ListAvailable PSTeams)[0]).ModuleBase)\Images" if (Test-Path $PathToImages) { Write-Verbose "Send-TeamChannelMessage - Image Path $PathToImages exists" $ImagePath = "$PathToImages\$($MessageType).jpg" if (Test-Path $ImagePath) { $Image = Get-Image $ImagePath Write-Verbose "Send-TeamChannelMessage - Image $ImagePath exists" $UseImage = $true } else { $UseImage = $false } } } If ($messageBody) { $TextOrSummary = 'text' $TextOrSummaryContents = $messageBody } If ($messageSummary) { $TextOrSummary = 'summary' $TextOrSummaryContents = $messageSummary } $potentialActions = @() foreach ($button in $buttons) { $potentialActions += @{ '@context' = 'http://schema.org' '@type' = 'ViewAction' name = $($button.Name) target = @("$($button.Value)") } } $TextOrSummaryContents = Optimize-JSONString $($TextOrSummaryContents) $body = ConvertTo-Json -Depth 6 @{ title = "$($messageTitle)" #themeColor = 'Green' $($TextOrSummary) = [System.Text.RegularExpressions.Regex]::Unescape($($TextOrSummaryContents)) sections = @( @{ activityTitle = "$($activityTitle)" activitySubtitle = "$activitySubtitle" activityImage = if ($UseImage) { "data:image/png;base64,$image" } else { '' } }, @{ title = $detailTitle facts = $details potentialAction = @( $potentialActions ) } ) } $Execute = Invoke-RestMethod -uri $uri -Method Post -body $body -ContentType 'application/json' Write-Verbose "Send-TeamChannelMessage - Execute $Execute" Write-Verbose "Send-TeamChannelMessage - Body $body" if ($Supress) { } else { return $body } } |