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 .EXAMPLE $SPList = New-SBAZServicePrincipal -ServicePrincipalName samtest1,sam1demo .OUTPUTS The function returns a Microsoft.Azure.Graph.RBAC.Version1_6.ActiveDirectory.PSADServicePrincipal object for each input Service Principal Name .LINK https://superwidgets.wordpress.com/ .NOTES Function by Sam Boutros v0.1 - 14 March 2018 #> [CmdletBinding(ConfirmImpact='Low')] Param([Parameter(Mandatory=$true)][String[]]$ServicePrincipalName) Begin { Connect-AzureRmAccount } Process { $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 $ServicePrincipal } } End { $SPList } } Export-ModuleMember -Function * -Variable * |