I have an Azure IoT Hub with a bunch of devices that our team's E2E tests generate. I want to purge the Hub every once in a while using the Azure CLI.
I am running the Azure CLI locally on Powershell, using the Azure IoT extension.
From my research, there is a way to get a list of all the devices in a hub printed to the console in JSON format:
az iot hub device-identity list --hub-name "test-hub"
And there is a way to delete a single device-identity:
az iot hub device-identity delete --device-id "test-id" --hub-name "test-hub"
How can I delete all the devices in the hub using the cli interfaces and some powershell commands?
Just run a For loop in PowerShell.
First install the Azure CLI for Powershell:
Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\AzureCLI.msi; Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'
Then add the Azure IoT extensions modules for PowerShell, log in to Azure, and change to the appropriate subscription (change <subscription_id>
) :
az extension add --name azure-cli-iot-ext
az login
az account set -s <subscription_id>
After that, run the following Foreach loop which will delete all devices (change test-hub
) :
$iotHubName = "test-hub"
$json = az iot hub device-identity list --hub-name $iotHubName
$devices = $json | ConvertFrom-Json
Foreach ($device in $devices)
{
az iot hub device-identity delete --device-id $device.deviceId --hub-name $iotHubName
}
Note: This is an extremely slow process as of 2019. You can follow the progress by looking up the IoT devices in the main portal.azure UI.