Skip to content

Instantly share code, notes, and snippets.

Last active October 25, 2020 05:45
What would you like to do?
PowerShell Function to create a Service Principal and return the script to onboard a machine to Azure Arc
param (
$ServicePrincipalName = 'AzureArcMachineOnboarding',
$OperatingSystem = 'Linux',
[Parameter(Mandatory = $true)]
[Parameter(Mandatory = $true)]
[Parameter(Mandatory = $true)]
[Parameter(Mandatory = $true)]
Select-AzSubscription -SubscriptionId $SubscriptionId
Write-Verbose -Message 'Registering provider namespaces: Microsoft.HybridCompute, Microsoft.GuestConfiguration'
Register-AzResourceProvider -ProviderNamespace 'Microsoft.HybridCompute'
Register-AzResourceProvider -ProviderNamespace 'Microsoft.GuestConfiguration'
Write-Verbose -Message ('Creating Service Principal {0}' -f $ServicePrincipalName)
$servicePrincipal = New-AzADServicePrincipal -DisplayName $ServicePrincipalName -Role "Azure Connected Machine Onboarding"
$credential = New-Object -TypeName pscredential -ArgumentList 'temp', $servicePrincipal.Secret
$servicePrincipalPassword = $credential.GetNetworkCredential().password
$servicePrincipalId = $servicePrincipal.ApplicationId
if ($OperatingSystem -eq 'Linux') {
$script = @"
# Download the installation package
wget -O ~/
# Install the hybrid agent
bash ~/
# Run connect command
sudo azcmagent connect \
--service-principal-id "$servicePrincipalId" \
--service-principal-secret "$servicePrincipalPassword" \
--resource-group "$ResourceGroup" \
--tenant-id "$TenantId" \
--location "$Location" \
--subscription-id "$SubscriptionId"
} else {
$script = @"
# Download the package
function download() {$ProgressPreference="SilentlyContinue"; Invoke-WebRequest -Uri -OutFile AzureConnectedMachineAgent.msi}
# Install the package
msiexec /i AzureConnectedMachineAgent.msi /l*v installationlog.txt /qn | Out-String
# Run connect command
& "`$env:ProgramFiles\AzureConnectedMachineAgent\azcmagent.exe" connect `
--service-principal-id "$servicePrincipalId" `
--service-principal-secret "$servicePrincipalPassword" `
--resource-group "$ResourceGroup" `
--tenant-id "$TenantId" `
--location "$Location" `
--subscription-id "$SubscriptionId"
return $script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment