PrivateFunctions/Add-UserToSlackChannel.ps1
<#
.SYNOPSIS This function adds a user to a channel in Slack. .DESCRIPTION This function adds a user to a channel in Slack. #> function Add-UserToSlackChannel { [CmdletBinding(PositionalBinding=$false)] [OutputType([Bool])] param( # The authentication token for Slack [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$token, # The name of the channel [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$channelName, # The user to add to the channel [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$userName, # Select the stream where the messages will be directed. [Parameter(Mandatory=$false)] [ValidateSet("Information", "Warning", "Error", "None")] [String]$outputStream = "Error" ) # Convert channelName and userName to corresponding IDs and verify that they exist $channelID = (Get-SlackChannel -Token $token -ChannelName $channelName).id if (!$channelID) { Write-OutputMessage "The channel '$($channelName)' cannot be found in Slack." -OutputStream $outputStream -ReturnMessage:$false return $false } $userID = (Get-SlackUser -Token $token -UserName $userName).id if (!$userID) { Write-OutputMessage "The user '$($userName)' cannot be found in Slack." -OutputStream $outputStream -ReturnMessage:$false return $false } # Prepare the API call parameters $invokeRestMethodParams = @{ Uri = "https://slack.com/api/channels.invite" Method = "POST" Headers = @{ "Content-Type" = "application/x-www-form-urlencoded" Authorization = "Bearer $($token)" } Body = @{ "channel" = "$($channelID)" "user" = "$($userID)" } } # Try to add the user to the channel Write-Information "Adding user '$($userName)' to channel '$($channelName)'." try { $response = Invoke-RestMethod @invokeRestMethodParams } catch { Write-OutputMessage "Exception occurred while adding user '$($userName)' to channel '$($channelName)'.`r`n$($_.Exception.Message)" -OutputStream $outputStream -ReturnMessage:$false return $false } # Verify that the addition is successful if ($response.ok) { Write-Information "User '$($userName)' was added to channel '$($channelName)'." return $true } else { Write-OutputMessage "Failed to add user '$($userName)' to channel '$($channelName)' with the error message:`r`n$($response.error)." -OutputStream $outputStream -ReturnMessage:$false return $false } } |