Kailash P
Kailash P

Reputation: 81

How to determine whether the script returned exit status code 1 or 0

I am running the below PowerShell script to give Azure IAM access to a storage account

#Read stdin as string
$jsonpayload = [Console]::In.ReadLine()

#Convert to JSON
$json = ConvertFrom-Json $jsonpayload

#Access JSON values
$userName = $json.userName
$resourceType = $json.resourceType
$resourceGroupName = $json.resourceGroupName

$objectid = (Get-AzureRmADUser -SearchString $userName).Id

$Result = New-AzureRmRoleAssignment -ObjectId $objectid -
RoleDefinitionName Reader -ResourceGroupName $resourceGroupName

if ($Result.ExitCode -ne 0) {
    exit 1
} else {
    # Return role result
    Write-Output '{ "roleResult" : "Role assigned successfully" }'
}

How to display a success message if there is no error, is there any alternate solution to handle this

I am getting the error

command "Powershell.exe" failed with no error message

if the scripts does not throw out any error.

Upvotes: 0

Views: 303

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

This statement is broken:

$Result = New-AzureRmRoleAssignment -ObjectId $objectid -
RoleDefinitionName Reader -ResourceGroupName $resourceGroupName

It should look like this:

$Result = New-AzureRmRoleAssignment -ObjectId $objectid -RoleDefinitionName Reader -ResourceGroupName $resourceGroupName

Also, according to the documentation the New-AzureRmRoleAssignment returns a PSRoleAssignment object, which doesn't have a property ExitCode, and you don't check the status of cmdlets like that anyway. PowerShell has a boolean automatic variable $? that indicates whether or not the last cmdlet call was successful or not, so your code should look like this:

$Result = New-AzureRmRoleAssignment -ObjectId $objectid -RoleDefinitionName Reader -ResourceGroupName $resourceGroupName

if ($?) {
    # Return role result
    Write-Output '{ "roleResult" : "Role assigned successfully" }'
} else {
    exit 1
}

Upvotes: 1

Related Questions