AutoRegTools.psm1 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. <#
  2. .DESCRIPTION
  3. For all subscriptions accessible to the logged in user, enable Automatic Registration with SQL IaaS Agent Extension
  4. Equivalent to the GUI method of enablement shown here:
  5. https://docs.microsoft.com/en-us/azure/azure-sql/virtual-machines/windows/sql-agent-extension-automatic-registration-all-vms?tabs=azure-cli
  6. .PREREQUISITES
  7. - The script needs to be run on Powershell 5.1 (Windows Only) and is incompatible with Powershell 6.x
  8. - The subscription whose VMs are to be registered, needs to be registered to Microsoft.SqlVirtualMachine resource provider first. This link describes
  9. how to register to a resource provider: https://docs.microsoft.com/azure/azure-resource-manager/resource-manager-supported-services
  10. - Run 'Connect-AzAccount' to first connect the powershell session to the azure account.
  11. - The Client credentials must have one of the following RBAC levels of access over the virtual machine being registered: Virtual Machine Contributor,Contributor or Owner
  12. - The user account running the script should have "Microsoft.SqlVirtualMachine/register/action" RBAC access over the subscriptions.
  13. - The user account running the script should have "Microsoft.Features/providers/features/register/action" RBAC access over the subscriptions.
  14. - The script requires Az powershell module (>=2.8.0) to be installed. Details on how to install Az module can be found
  15. here : https://docs.microsoft.com/powershell/azure/install-az-ps?view=azps-2.8.0
  16. It specifically requires Az.Subscription module which comes as part of Az module (>=2.8.0) installation.
  17. - The script requires the EnableBySubscription script to be accessible and executable.
  18. .EXAMPLE
  19. Option 1: EnableAllSubscriptions
  20. Option 2: EnableSubscriptionList @('sub1guid','sub2guid',...)
  21. Option 3: EnableSubscriptionList [Enter] then enter paste in subscription guid when prompted
  22. #>
  23. using namespace System.Collections.Generic
  24. function EnableAllSubscriptions (
  25. ) {
  26. $subscriptionIdList = [List[string]]@()
  27. # Get a list of all subscriptions to which the current user has access.
  28. # NOTE: This step does not verify RBAC permissions. Subscriptions without adequate permission will output an error
  29. $subInAcc = Get-AzSubscription
  30. # Build a string array containing the subscription GUIDs
  31. ForEach($sub in $subInAcc)
  32. {
  33. $subName = $sub | Select-Object -ExpandProperty Name
  34. $subscriptionIdList.Add($sub)
  35. }
  36. # Pass the list of subs to the main function
  37. EnableSubscriptionList -SubscriptionList $subscriptionIdList.ToArray()
  38. }
  39. function EnableSubscriptionList {
  40. [CmdletBinding(DefaultParameterSetName = 'SubscriptionList')]
  41. Param
  42. (
  43. [Parameter(Mandatory = $true)]
  44. [ValidateNotNullOrEmpty()]
  45. [string[]]
  46. $SubscriptionList
  47. );
  48. #Array of objects for storing failure subscriptionIds and failure reasons.
  49. $FailedRegistrations = @();
  50. # Register subscriptionIds to Automatic Registraion.
  51. # https://docs.microsoft.com/th-th/powershell/azure/install-az-ps?view=azps-3.8.0#install-the-azure-powershell-module.
  52. # Check if AzureRm is already installed and use that module if it is already available.
  53. if ($PSVersionTable.PSEdition -eq 'Desktop' -and (Get-Module -Name AzureRM -ListAvailable)) {
  54. Write-Host "AzureRM is already installed. Registering using AzureRm commands";
  55. Write-Host "Please login to your account which have access to the listed subscriptions";
  56. $Output = Connect-AzureRmAccount -ErrorAction Stop;
  57. foreach ($SubscriptionId in $SubscriptionList) {
  58. Write-host "`n`n--------------------$SubscriptionId----------------------------`n`n";
  59. try {
  60. Write-Host "Setting powershell context to subscriptionid: $SubscriptionId";
  61. $Output = Set-AzureRmContext -SubscriptionId $SubscriptionId -ErrorAction Stop;
  62. Write-Host "Registering subscription($SubscriptionId) to Microsoft.SqlVirtualMachine Resource provider";
  63. $Output = Register-AzureRmResourceProvider -ProviderNamespace Microsoft.SqlVirtualMachine -ErrorAction Stop;
  64. Write-Host "Registering subscription($SubscriptionId) to AFEC";
  65. $Output = Register-AzureRmProviderFeature -FeatureName BulkRegistration -ProviderNamespace Microsoft.SqlVirtualMachine -ErrorAction Stop;
  66. }
  67. Catch {
  68. $message = $_.Exception.Message;
  69. Write-Error "We failed due to complete $SubscriptionId operation because of the following reason: $message";
  70. # Store failed subscriptionId and failure reason.
  71. $FailedRegistration = @{ };
  72. $FailedRegistration.Add("SubscriptionId", $SubscriptionId);
  73. $FailedRegistration.Add("Errormessage", $message);
  74. $FailedRegistrations += New-Object -TypeName psobject -Property $FailedSubscriptionId;
  75. }
  76. };
  77. }
  78. else {
  79. # Since AzureRm module is not availavle, we will use Az module.
  80. Write-Host "Installing Az powershell module if not installed already."
  81. Install-Module -Name Az -AllowClobber -Scope CurrentUser;
  82. Write-Host "Please login to your account which have access to the listed subscriptions";
  83. $Output = Connect-AzAccount -ErrorAction Stop;
  84. foreach ($SubscriptionId in $SubscriptionList) {
  85. Write-host "`n`n--------------------$SubscriptionId----------------------------`n`n"
  86. try {
  87. Write-Host "Setting powershell context to subscriptionid: $SubscriptionId";
  88. $Output = Set-AzContext -SubscriptionId $SubscriptionId -ErrorAction Stop;
  89. Write-Host "Registering subscription($SubscriptionId) to Microsoft.SqlVirtualMachine Resource provider";
  90. $Output = Register-AzResourceProvider -ProviderNamespace Microsoft.SqlVirtualMachine -ErrorAction Stop;
  91. Write-Host "Registering subscription($SubscriptionId) to AFEC";
  92. $Output = Register-AzProviderFeature -FeatureName BulkRegistration -ProviderNamespace Microsoft.SqlVirtualMachine -ErrorAction Stop;
  93. }
  94. Catch {
  95. $message = $_.Exception.Message;
  96. Write-Error "We failed due to complete $SubscriptionId operation because of the following reason: $message";
  97. # Store failed subscriptionId and failure reason.
  98. $FailedRegistration = @{ };
  99. $FailedRegistration.Add("SubscriptionId", $SubscriptionId);
  100. $FailedRegistration.Add("Errormessage", $message);
  101. $FailedRegistrations += New-Object -TypeName psobject -Property $FailedSubscriptionId;
  102. }
  103. };
  104. }
  105. # Failed subscription registration and its reason will be stored in a csv file(RegistrationErrors.csv) for easy analysis.
  106. # The file should be available in current directory where this .ps1 is executed
  107. $FailedRegistrations | Export-Csv -Path RegistrationErrors.csv -NoTypeInformation
  108. }