I needed to run a PowerShell cmdlet in an Azure Devops pipeline. The cmdlet in question was New-AzRoleAssignment, but the cmdlet itself isn’t important. What is important is that I needed to pass the object ID of a service principal to the command. Even though I was pretty sure the syntax and everything was correct, I got a “Operation returned an invalid status code ‘BadRequest’” error when the PowerShell was run (inside an Azure PowerShell task):
To test the script, I opened an Azure CLI in the Azure Portal and ran the same script over there. I got the same error, which isn’t exactly helpful.

After some searching, I found a helpful comment in a thread suggesting to turn on debugging with the following command:
$DebugPreference = "Continue"
When running the same PowerShell command again, you’ll now get a full dump and the actual error message:

The error states that “Principals of type Application cannot validly be used in role assignments”. I’m pretty sure that I’ve used service principals before in role assignments, so what is going on? When a service principal is created (for example when creating a service connection in Azure Devops), there are actually two objects created with the same name: an app registration and an enterprise application. This is the app registration:

It’s this object ID that I referenced in the PowerShell script, but as it turns out an app registration cannot be used for a role assignment, you need the enterprise application object ID. However, when you got to the enterprise applications in Azure Entra ID, it’s possible you don’t see your service principal listed. You need to remove the following filter from the screen:

Now you will get a full list and your service principal should be there. When you click on it, you’ll be taken to the following page:

It’s this object ID that you need for the PowerShell script. You can also find the enterprise application if your service principal already has a role assignment somewhere else.

The ID listed over there is not the object ID, but the application ID. When you click on the service principal, it should take you to the page with the correct object ID. However, it’s possible you don’t have read access to enterprise applications in the Azure Entra ID of your environment. But not to worry, you can simply find the object ID in the URL:

The post Bad Request Error when Running PowerShell Command in Azure Devops first appeared on Under the kover of business intelligence.