AZSBTools.psm1

function New-SBAZServicePrincipal {
<#
 .SYNOPSIS
  Function to create Azure AD Service Principal
 
 .DESCRIPTION
  Function to create Azure AD Service Principal
  The use case intended for this function is to use the Service Principal to run PowerShell scripts against an Azure subscription
 
 .PARAMETER ServicePrincipalName
  One or more Service Principal Names
 
 .PARAMETER Environment
  Name of the Azure cloud. This parameter default to Azure Commercial cloud.
  As of 15 March 2018 that list is:
    AzureGermanCloud
    AzureCloud
    AzureUSGovernment
    AzureChinaCloud
    To see an updated list, use:
        (Get-AzureRMEnvironment).Name
 
 .PARAMETER Role
  This parameter is used to assign Role/Permissions for te Service Principal in the current subscription.
  The default value is 'Owner' role.
  As of 16 March 2018 the following default roles are defined:
    API Management Service Contributor
    Application Insights Component Contributor
    Automation Operator
    BizTalk Contributor
    Classic Network Contributor
    Classic Storage Account Contributor
    Classic Storage Account Key Operator Service Role
    Classic Virtual Machine Contributor
    ClearDB MySQL DB Contributor
    Contributor
    Cosmos DB Account Reader Role
    Data Factory Contributor
    Data Lake Analytics Developer
    DevTest Labs User
    DNS Zone Contributor
    DocumentDB Account Contributor
    Intelligent Systems Account Contributor
    Log Analytics Contributor
    Log Analytics Reader
    Network Contributor
    New Relic APM Account Contributor
    Owner
    Reader
    Redis Cache Contributor
    Scheduler Job Collections Contributor
    Search Service Contributor
    Security Manager
    SQL DB Contributor
    SQL Security Manager
    SQL Server Contributor
    Storage Account Contributor
    Storage Account Key Operator Service Role
    Traffic Manager Contributor
    User Access Administrator
    Virtual Machine Contributor
    Web Plan Contributor
    Website Contributor
  For more details on roles, type in:
    Get-AzureRmRoleDefinition | select name,description,actions | Out-GridView
 
 .EXAMPLE
  $SPList = New-SBAZServicePrincipal -ServicePrincipalName samtest1,sam1demo
 
 .OUTPUTS
  The function returns a PS Object for each input Service Principal Name containing the following properties:
    ServicePrincipalName
    TenantId
    Environment
    Role
 
 .LINK
  https://superwidgets.wordpress.com/2018/03/15/new-sbazserviceprincipal-cmdlet-to-create-new-azure-ad-service-principal-added-to-azsbtools-powershell-module/
 
 .NOTES
  Function by Sam Boutros
  v0.1 - 14 March 2018
  v0.2 - 15 March 2018 - Added 'Environment' parameter
  v0.3 - 16 March 2018 - Added 'Role' parameter, changed output to a custom PS Object
#>


    [CmdletBinding(ConfirmImpact='Low')] 
    Param(
        [Parameter(Mandatory=$true)][String[]]$ServicePrincipalName,
        [Parameter(Mandatory=$false)][ValidateSet('AzureCloud','AzureUSGovernment','AzureGermanCloud','AzureChinaCloud')][String]$Environment = 'AzureCloud',
        [Parameter(Mandatory=$false)][String]$Role = 'Owner'
    )

    Begin { 
        $Subscription = Connect-AzureRmAccount -Environment $Environment  
    }

    Process {
        
        if ($Subscription.Context.Subscription.Name) { 

            Write-Log 'Identified',$Subscription.Context.Subscription.Name,'subscription in the',$Subscription.Context.Environment.Name,'cloud' Green,Cyan,Green,Cyan,Green

            $SPList = foreach ($AppName in $ServicePrincipalName) {

                $AppCred = Get-SBCredential -UserName $AppName
        
                #region Create/Validate Azure AD App
                Remove-Variable App -EA 0 
                if ($App = Get-AzureRmADApplication -DisplayName $AppName) {
                    Write-Log 'Validated app:',$App.Displayname Green,Cyan 
                } else {
                    $App = New-AzureRmADApplication -DisplayName $AppName -IdentifierUris $AppName
                    Write-Log 'Created app:',$App.Displayname Green,Cyan 
                }            
                #endregion

                #region Create/Validate Azure AD Service Principal
                Remove-Variable ServicePrincipal -EA 0 
                if ($ServicePrincipal = Get-AzureRmADServicePrincipal | where { $PSItem.ApplicationId -eq $App.ApplicationId.Guid }) {
                    Write-Log 'Validated Service Principal:',($ServicePrincipal.SerVicePrincipalNames -join ', ') Green,Cyan 
                } else {
                    $ServicePrincipal = New-AzureRmADServicePrincipal -ApplicationId $App.ApplicationId.Guid -Password $AppCred.Password
                    Write-Log 'Created Service Principal:',($ServicePrincipal.SerVicePrincipalNames -join ', ') Green,Cyan 
                }            
                #endregion

                #region Assign Role (Permissions)
                Write-Log 'Assigning role',$Role Green,Cyan -NoNewLine
                $Result = try {
                    New-AzureRmRoleAssignment -ObjectId $ServicePrincipal.Id -RoleDefinitionName $Role -Scope "/subscriptions/$($Subscription.Context.Subscription.Id)" -EA 1
                    Write-Log 'done' Green
                } catch {
                    Write-Log $PSItem.Exception.Message Yellow
                }
                #endregion

                [PSCustomObject][Ordered]@{
                    ServicePrincipalName = $AppName
                    TenantId             = (Get-AzureRmTenant).Id 
                    Environment          = $Environment
                    Role                 = $Role
                }

            }
                    
        } else {
            Write-Log 'No subscriptions found for account',$Subscription.Context.Account.Id,'in the',$Subscription.Context.Environment.Name,'cloud' Magenta,Yellow,Magenta,Yellow,Magenta
        }        

    }

    End {
        $SPList
    }
}


Export-ModuleMember -Function * -Variable *