Functions/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. The scope required to call this function is "channels:write". #> 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 ) # Retrieve the ID for the specified channel and user and verify that they exist $channelID = (Get-SlackChannel -Token $token -ChannelName $channelName).id if (!$channelID) { throw "The channel '$($channelName)' cannot be found in Slack." } $userID = (Get-SlackUser -Token $token -UserName $userName).id if (!$userID) { throw "The user '$($userName)' cannot be found in Slack." } # 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)" } } # Invoke the call $response = Invoke-RestMethod @invokeRestMethodParams # Verify that the addition is successful if ($response.ok) { return $true } else { throw "Failed to add user '$($userName)' to channel '$($channelName)' with the error message:`r`n$($response.error)." } } |