Written by

Ravishankar

Share

  

Category

see all categories
intranet as a service

How to Register IoT Device in Azure IoT Hub Using PowerShell

In this article, we are going to see how to add IoT device in azure IoT Hub using Azure PowerShell cmdlets. IoT hub is a cloud platform services which supports multiple protocols and open-source SKD’s. It is used to connect, manage, and monitor billions of IoT devices and securely connects the devices to develop IoT applications. 

Prerequisite 

Before you begin to utilize PowerShell to oversee the Azure PowerShell, ensure that the Azure PowerShell has been installed. If not installed, here is an article on How to install Azure PowerShell module and Install the Azure IoT module . You need to do this only once for each computer from which you are running Azure PowerShell commands. 

Connecting to Azure Portal: 

Connect to Azure Portal using Connect-AzureRmAccount cmdlet.  

Connect-AzureRmAccount  

Select the Azure IoT Hub  

Select Azure IoT Hub where we want to register the device. You can select the IoT Hub that already created by using the Get-AzureRmIotHub cmdlets. The required parameter are, 

ResourceGroupName - Specify the name of the resource group. 
Name - Specify the name of the IoT Hub

If you want to create the new IoT Hub, here is an article How to Create Azure IoT Hub Using Azure PowerShell . 

Get Azure IoT Hub Key  

You can get the Azure IoT Hub Key using the Get-AzureRmIotHubKey  cmdlets. The required parameters are, 

ResourceGroupName - Specify the name of the resource group. 
Name - Specify the name of the IoT Hub. 
KeyName - Specify the IoT Hub Key name (iothubowner, service, device).

Register New IoT Device  

You can register the new Azure IoT device using the “Register-IoTDevice cmdlets. The required parameters are, 

iotConnString  Specify the IoT Hub Connection string. 
deviceId   Specify the device Id. 

Final Code : 

Connect-AzureRmAccount 

$RGName ="MyIOTRG" 

$location="East US" 

$IoTHubName = "jsiotconnect" 

$IoTKeyName = "iothubowner" 

$IoTHub = Get-AzureRmIotHub -Name $IoTHubName -ResourceGroupName $RGName 

$IoTHubKey = Get-AzureRmIotHubKey -ResourceGroupName $RGName -Name $IoTHubName -KeyName $IoTKeyName  

$IoTConnectionString  = "HostName=$($IoTHubName).azure-devices.net;SharedAccessKeyName=$($IoTKeyName);SharedAccessKey=$($IoTHubKey.PrimaryKey)" 

# New DeviceID 

$newDeviceID = "jsiotdevice_004" 

$deviceParams = @{  

     iotConnString = $IoTConnectionString 

    deviceId = $newDeviceID 

} 

$device = Register-IoTDevice @deviceParams 

$device   

I hope you have learned how to register a new IoT device in Azure IoT Hub using Azure PowerShell programmatically. Feel free to fill up the comment box below if you need any assistance.