Archive Channels in Slack with Powershell

So my problem is that we’ve controlled the permissions in our account so only Admins can archive channels in Slack. Slack allows all users to create channels, great way to get things going but can get messy real QUICK. Our company has hundreds of abandoned channels and I needed a bulk method to archive them all. I haven’t worked with Slack’s API before but after about an hour with a developer at our company I could do some basics. Since I am most literate in PowerShell we set this up as a way to accomplish it. More details from Slack can be found at channels.archive

You can install the PowerShell module for the Slack API with this:

Install-Module PSSlack -Confirm:$False

Next up is then to setup all your variables, I’ll give a brief explanation of each:
$Token: Slack Legacy Tokens
$AllChannels: We’re going to get all channels that aren’t already archived
$InactiveChannels: Now were going to only get the channels where the Members are zero
$InactiveChannelsID: Finally we need to get the unique identifier for each channel called the ID

First let’s just get comfortable with getting all the channels so you can understand what you will archive. This will allow you to output how many channels, then also export all of the details to a CSV so you can review.

$Token = "xoxp-########-########-########-########"
$AllChannels = Get-SlackChannel -Token $Token -Paging -ExcludeArchived
$InactiveChannels = $AllChannels | Where-Object {$_.MemberCount -eq 0}
$InactiveChannels.count
$AllChannels | Where-Object {$_.MemberCount -eq 0} | Export-Csv C:\Scripts\Slack\InactiveChannels.csv -NoTypeInformation

Once you’re comfortable with all of these results and you are ready to take action on them use this to archive each of the channels with zero members. Archiving a channel can be reversed, you select any archived channel and make it active again.

$Token = "xoxp-########-########-########-########"
$AllChannels = Get-SlackChannel -Token $Token -Paging -ExcludeArchived
$InactiveChannels = $AllChannels | Where-Object {$_.MemberCount -eq 0}
$InactiveChannelsID = $InactiveChannels | Select -ExpandProperty ID

ForEach ($ID in $InactiveChannelsID) 
{
    $SlackURL = "https://slack.com/api/channels.archive?token=$Token&channel=$ID&pretty=1"
    Invoke-WebRequest -Uri $SlackURL -Headers @{"Authorization"="Bearer $Token"}
}

Let me know how it goes! There’s a ton you can do with Slack’s API so I’m just getting started. Hope this is a practical example of something that could be useful to you.