PrivateFunctions/Remove-UserFromSlackChannel.ps1

<#
.SYNOPSIS
    This function removes a user from a channel in Slack.
.DESCRIPTION
    This function removes a user from a channel in Slack.
#>

function Remove-UserFromSlackChannel {
    [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 remove from 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.kick"
        Method  = "POST"
        Headers = @{
            "Content-Type" = "application/x-www-form-urlencoded"
            Authorization  = "Bearer $($token)"
        }
        Body    = @{
            "channel" = "$($channelID)"
            "user"    = "$($userID)"
        }
    }

    # Try to remove the user from the channel
    Write-Information "Removing user '$($userName)' from channel '$($channelName)'."
    try {
        $response = Invoke-RestMethod @invokeRestMethodParams
    }
    catch {
        Write-OutputMessage "Exception occurred while removing user '$($userName)' from channel '$($channelName)' in Slack.`r`n$($_.Exception.Message)" -OutputStream $outputStream -ReturnMessage:$false
        return $false
    }

    # Verify that the removal is successful
    if ($response.ok) {
        Write-Information "User '$($userName)' was removed from channel '$($channelName)'."
        return $true
    }
    else {
        Write-OutputMessage "Failed to remove user '$($userName)' from '$($channelName)' with the error message:`r`n$($response.error)." -OutputStream $outputStream -ReturnMessage:$false
        return $false
    }
}