Set-AzVMCustomScriptExtension in catch? - azure

Attempting to add an extension when not detected but keep failing to find the secret sauce to get this to work. Mind you I am a BASH guy and this is a first foray into PowerShell..
#requires -version 2
# Required parameter $subscription: name of the subscription to enable Custom Script Extensions in
param (
# NOTE: See below for reason...
# [Parameter(Mandatory = $true)] [String] $subscription
# NOTE: Prompting is great for using the script interactively, but if this will also be executed
# from a build server or ...
# NOTE: Once the parameter is marked as mandatory PowerShell it will prompt for value. That said,
# if you remove the mandatory attribute then you can set a default value as a T_THROW ...
# NOTE: This _does_ contain shortcomings if this will be used as a pipeline param ...
# https://stackoverflow.com/questions/33600279/is-it-possible-to-force-powershell-script-to-throw-if-a-required-pipeline-para
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$SubscriptionName=$(Throw "`SubscriptionName` is mandatory, please provide a value...")
)
# Connect to the current Azure account
Write-Output "Pulling Azure account credentials..."
Start-Process "https://microsoft.com/devicelogin" # steals focus...
# Login to Azure account
Connect-AzAccount
# Set the active subscription
$null = Get-AzSubscription -SubscriptionName "$SubscriptionName" |Set-AzContext
# TODO: error handling
$vms = Get-AzVM
$cseName = "VulnerabilityManagementTools"
ForEach ($vm in $vms) {
try {
$cseStatus = Get-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Name $cseName `
-Status
}
catch {
Write-Output "Enabling Custom Script Extension for $vm."
Set-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroup `
-Location $vm.Location `
-VMName $vm.Name `
-Name $cseName `
-TypeHandlerVersion "1.1" `
-StorageAccountName "VulnerabilityManagementTools" `
-FileName "VulnerabilityManagementInstaller.ps1" `
-ContainerName "VulnerabilityManagementTools"
}
}
End up err'ing out with
PS /.../automation-scripts> ./EnableCustomScriptExtension.ps1 SubscriptionName
Pulling Azure account credentials...
WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXX to authenticate.
Account SubscriptionName TenantId Environment
------- ---------------- -------- -----------
XXXX#analytics.com SubName XXXXXX-XXXX AzureCloud
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{NAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{NAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/XXXXX/extensions/VulnerabilityManagementTools' under resource group '{RESOURCE_GROUPNAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/XXXX/extensions/VulnerabilityManagementTools' under resource group '{RESOURCE_GROUPNAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand
Get-AzVMCustomScriptExtension : The Resource 'Microsoft.Compute/virtualMachines/{VMName}/extensions/VulnerabilityManagementTools' under resource group '{RESOURCEX_GROUPNAME}' was not found.
ErrorCode: ResourceNotFound
ErrorMessage: The Resource 'Microsoft.Compute/virtualMachines/{VMName}/extensions/VulnerabilityManagementTools' under resource group '{RESOURCEX_GROUPNAME}' was not found.
ErrorTarget:
StatusCode: 404
ReasonPhrase: Not Found
At /.../automation-scripts/EnableCustomScriptExtension.ps1:59 char:18
+ $cseStatus = Get-AzVMCustomScriptExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzVMCustomScriptExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.GetAzureVMCustomScriptExtensionCommand`

In your case, you just need to use the if(){}else{} statement, try the script as below instead of the ForEach part of yours, it works fine on my side.
ForEach ($vm in $vms) {
$cseStatus = Get-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroupName `
-VMName $vm.Name `
-Name $cseName `
-Status `
-ErrorAction SilentlyContinue
if ($cseStatus){
Write-Host "The extension has been set for" $vm.Name
}else{
Write-Host "Enabling Custom Script Extension for" $vm.Name
Set-AzVMCustomScriptExtension `
-ResourceGroupName $vm.ResourceGroup `
-Location $vm.Location `
-VMName $vm.Name `
-Name $cseName `
-TypeHandlerVersion "1.1" `
-StorageAccountName "VulnerabilityManagementTools" `
-FileName "VulnerabilityManagementInstaller.ps1" `
-ContainerName "VulnerabilityManagementTools"
}
}
Test result:

You'll need to create an Azure AD Service Principal using password authentication and use the credentials of this to pass to the Connect-AzAccount cmdlet as follows:
$credentials = Get-Credential
Connect-AzAccount -ServicePrincipal -Credentials $credentials
The service account will need to have the necessary permissions to use the Set-AzVMCustomScriptExtensions cmdlet.
More information on creating the service account here:
https://learn.microsoft.com/en-us/powershell/azure/create-azure-service-principal-azureps?view=azps-2.8.0

Related

I need to Specify OS Disk Name while Creating Azure VMSS using PowerShell

I want to Specify OS Disk Name while Creating VMSS using PowerShell to overcome the random OS Disk name like "VMSSNAME_1686_disk1_b5f021da0ba7409fbe7d028bdd50".
Command :
Set-AzVmssStorageProfile $vmssConfig `
-OsDiskCreateOption "FromImage" `
-ImageReferenceId $galleryImage.Id -OsDiskName $OSDiskName
# Set up information for authenticating with the virtual machine
Set-AzVmssOsProfile $vmssConfig `
-AdminUsername $username `
-AdminPassword $Password `
-ComputerNamePrefix "UKSSPAG"
# Attach the virtual network to the config object
Add-AzVmssNetworkInterfaceConfiguration -VirtualMachineScaleSet $vmssConfig -Name "NICConfig" -Primary $true -IPConfiguration $ipConfig
# Create the scale set with the config object (this step might take a few minutes)
New-AzVmss -ResourceGroupName $resourceGroup -VMScaleSetName $scaleSetName -VirtualMachineScaleSet $vmssConfig
Error :
New-AzVmss : Parameter 'osDisk.name' is not allowed.
ErrorCode: InvalidParameter
ErrorMessage: Parameter 'osDisk.name' is not allowed.
ErrorTarget: osDisk.name
StatusCode: 400
ReasonPhrase: Bad Request
OperationID : e97450a3-ed89-46f8-84fa-6779a002a3e9
At line:1 char:1
+ New-AzVmss -ResourceGroupName $resourceGroup -VMScaleSetName $scaleSe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzVmss], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.Automation.NewAzureRmVmss

How to add event subscription to Azure storage using New-AzEventGridSubscription?

I am trying to add subscription to storage account using New-AzEventGridSubscription. The subscription should be triggered by blob modification in a container and put message to a certain queue. I created the following script:
$ResourceGroup = "test"
$includedEventTypes = "Microsoft.Storage.BlobCreated", "Microsoft.Storage.BlobDeleted"
New-AzEventGridSubscription `
-ResourceId "/subscriptions/[id]/resourceGroups/[group]/providers/Microsoft.Storage/storageAccounts/[name]" `
-EventSubscriptionName DummyName `
-Endpoint "/subscriptions/[id]/resourceGroups/[group]/providers/Microsoft.Storage/storageAccounts/[name]/queueServices/default/queues/my-queue" `
-ResourceGroup $ResourceGroup `
-EndpointType "storagequeue" `
-SubjectBeginsWith "prefix" `
-SubjectEndsWith "suffix"
but it throws an error:
New-AzEventGridSubscription : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ New-AzEventGridSubscription `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-AzEventGridSubscription], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.Azure.Commands.EventGrid.NewAzureEventGridSubscription
I made similar command to add subscription to a custom topic, which worked well:
New-AzEventGridSubscription `
-ResourceGroup $ResourceGroup `
-EventSubscriptionName SubscriptionName `
-TopicName MyCustomTopic `
-EndpointType "storagequeue" `
-Endpoint "/subscriptions/[id]/resourceGroups/[group]/providers/Microsoft.Storage/storageAccounts/[account]/queueServices/default/queues/my-queue" `
-SubjectBeginsWith "prefix" `
-SubjectEndsWith "suffix"
I tried several modifications, but to no avail. What am I doing wrong?
After throwing out "ResourceGroup" parameter, reordering other parameters, and putting some arguments into variables, I finally managed to get my script up and running... If anyone ever needs similar stuff, here it is:
$subscriptionId = "<id>"
$ResourceGroup = "<group>"
$includedEventTypes = "Microsoft.Storage.BlobCreated", "Microsoft.Storage.BlobDeleted"
$storageAccount = "<account name>"
$endpoint = "/subscriptions/"+$subscriptionId+"/resourceGroups/"+$ResourceGroup+"/providers/Microsoft.Storage/storageAccounts/"+$storageAccount+"/queueServices/default/queues/my-queue"
$resourceId = "/subscriptions/"+$subscriptionId+"/resourceGroups/"+$ResourceGroup+"/providers/Microsoft.Storage/storageAccounts/"+$storageAccount
$subject = "prefix"
New-AzEventGridSubscription `
-EventSubscriptionName MySubscriptionName `
-Endpoint $endpoint `
-ResourceId $resourceId `
-EndpointType "storagequeue" `
-SubjectBeginsWith $subject `
-SubjectEndsWith "suffix" `
-IncludedEventType $includedEventTypes

error - WARNING: The version '1.9.4' of module 'Az.Accounts' is currently in use. Powershell script run on VM in Azure cloud

Here is my powershell command sequence.
PS C:\Application01>Install-Module -Name Az -AllowClobber -Scope AllUsers
PS C:\Application01>Connect-AzAccount ### this prompts me for my azure logon
PS C:\Application01>Update-Module -Name Az
PS C:\Application01>.\Publish-Application01.ps1 -action "Deploy" `
-azureAccountApplicationId "a3XXXXXXXXXXXXXXXXXXXXXXXX76" `
-azureAccountPassword "43XXXXXXXXXXXXXXXXXXXXXXXXXXXm" `
-package "C:\Application01\Application01.server.Web.zip" `
-azureSubscriptionId "c27XXXXXXXXXXXXXXXXXXXXXXXXX32" `
-azureAccountTenantId "41XXXXXXXXXXXXXXXXXXXXXXXXX1d" `
-hostAdminPassword "XXXXXXXXXXXX" `
-defaultTenantAdminPassword "XXXXXXXXXXX" `
-resourceGroupName "RG01" `
-appServiceName "Applicationservice01" `
-nugetRepositoryType "Composite" `
-storageType "Azure" `
-storageLocation "DefaultEndpointsProtocol=https://XXXXXXXXX" `
-appSettings #{"Telemetry.Enabled"="false"} `
-verbose
WARNING: The version '1.9.4' of module 'Az.Accounts' is currently in use. Retry the operation after closing the applications.
WARNING: The provided service principal secret will be included in the 'AzureRmContext.json' file found in the user profile ( C:\Users\zzadmin\.Azure ). Please ensure that this directory has appropriate protections.
Connect-AzAccount : The provided account a3XXXXXXXXXXXXXXXXXXXX76 does not have access to subscription ID "c2XXXXXXXXXXXXXXXXXXXXXXXX2". Please try logging in with different credentials or a different subscription ID.
At C:\Application01\Publish-Application01.ps1:577 char:9
+ if (Connect-AzAccount -Environment AzureUSGovernment -ServicePrin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Connect-AzAccount], PSInvalidOperationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
XXXXXXXXXXXXXXXXXX
Line 577 >>> -ServicePrincipal --
my understanding is a prompt will appear to enter a value for ServicePrincipal.
Here is the azure Function.
function AuthenticateToAzure {
$securePassword = $azureAccountPassword | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($azureAccountApplicationId, $securePassword)
if (Connect-AzAccount -Environment AzureUSGovernment -ServicePrincipal -SubscriptionId $azureSubscriptionId -TenantId $azureAccountTenantId -Credential $credential){
Write-Host "Logged in to Az" -ForegroundColor Green
} else {
Write-Error "Failed to log in to Az"
Exit 1
}
XXXXXXXXXXXXXX
I have tried rebooting the VM and error still appears.
The zzadmin account on the VM is a local administrator.
User account logon Azure is the owner role.

Why am i getting "New-AzSqlDatabaseImport : Not found: Entity not found to invoke import"

I have a script to handle some parameters and deploy an arm template with those parameters, and then create a database using a bacpac file in my storage account. When my script is trying to invoke the cmdlet "New-AzSqlDatabaseImport" i'm getting "NotFound: Entity not found to invoke import"
I have trying updating all of my Az modules, and tried to run the cmdlet manually and fill in the parameters manually.
Write-Host "Creating database and importing data"
$bloblink = (Get-AzStorageAccount -ResourceGroupName $ResourceGroup -Name $StorageName).PrimaryEndpoints.Blob
$uri = $bloblink + $containerName + "/" + $bacpacFile
$importRequest = New-AzSqlDatabaseImport `
-ResourceGroupName $ResourceGroup `
-ServerName $SQLServer `
-DatabaseName $database_ql_name `
-DatabaseMaxSizeBytes $databaseMaxSizeBytes `
-StorageKeyType "StorageAccessKey" `
-StorageKey $(Get-AzStorageAccountKey -ResourceGroupName $ResourceGroup -StorageAccountName $StorageName).Value[0] `
-StorageUri $uri `
-Edition $DatabaseEdition `
-ServiceObjectiveName $DatabaseSize `
-AdministratorLogin $dbUsername `
-AdministratorLoginPassword $dbPassword
I expect it to start a job on Azure to create the database and start the import job.
This is the error im getting instead (i replaced the full path).
At *PATH*/Deployment.ps1:262 char:18
+ $importRequest = New-AzSqlDatabaseImport `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzSqlDatabaseImport], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Sql.ImportExport.Cmdlet.NewAzureSqlDatabaseImport
I just encountered the same error. I found that the -ServerName argument is case-sensitive. So check your $SQLServer-variable.

Azure PowerShell script does not work when change to a different Azure Subscription

I am experiencing a very strange problem. I recently switched Azure subscription from free trial to pay-as-you-go. The PowerShell script i wrote to create Azure Resource Group, Azure Data Factory, Azure Active Directory App Azure SQL Server, Azure SQL Database does not work. below is the sample code from script and error messages
New-AzResourceGroup Test2ResourceGroupName2 -location 'westeurope'
$AzADAppName = "TestADApp1"
$AzADAppUri = "https://test.com/active-directory-app"
$AzADAppSecret = "TestSecret"
$AzADApp = Get-AzADApplication -DisplayName $AzADAppName
if (-not $AzADApp) {
if ($AzADApp.IdentifierUris -ne $AzADAppUri) {
$AzADApp = New-AzADApplication -DisplayName $AzADAppName -HomePage $AzADAppUri -IdentifierUris $AzADAppUri -Password $(ConvertTo-SecureString -String $AzADAppSecret -AsPlainText -Force)
}
}
New-AzResourceGroup : Your Azure credentials have not been set up or have expired, please run Connect-AzAccount to set up your Azure credentials.
At line:1 char:1
+ New-AzResourceGroup Test2ResourceGroupName2 -location 'westeurope'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzResourceGroup], ArgumentException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceGroupCmdlet
Get-AzADApplication : User was not found.
At line:6 char:12
+ $AzADApp = Get-AzADApplication -DisplayName $AzADAppName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-AzADApplication], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ActiveDirectory.GetAzureADApplicationCommand
New-AzADApplication : User was not found.
At line:11 char:20
+ ... $AzADApp = New-AzADApplication -DisplayName $AzADAppName -HomePage $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-AzADApplication], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ActiveDirectory.NewAzureADApplicationCommand
However if i execute this command in Azure Cloud Shell it works.
New-AzResourceGroup Test2ResourceGroupName -location 'westeurope'
I am also able to create Resource Group and other resources in Azure Portal. We cannot use portal and we have to use powershell due to company policy. could anyone help why PowerShell is not working
Here is the full script as requested in comments
Connect-AzAccount -TenantID xxxxx-xxx-xxx-xxxxx-xxxxx
# Creating Azure Active Directory App
$AzADAppName = "xxxxx-active-directory-app"
$AzADAppUri = "https://xxxxx.com/xxxxx-app"
$AzADAppSecret = "xxxxx"
$AzADApp = Get-AzADApplication -DisplayName $AzADAppName
if (-not $AzADApp) {
if ($AzADApp.IdentifierUris -ne $AzADAppUri) {
$AzADApp = New-AzADApplication -DisplayName $AzADAppName -HomePage $AzADAppUri -IdentifierUris $AzADAppUri -Password $(ConvertTo-SecureString -String $AzADAppSecret -AsPlainText -Force)
$AzADServicePrincipal = New-AzADServicePrincipal -ApplicationId $AzADApp.ApplicationId
# Assign the Contributor RBAC role to the service principal
# If you get a PrincipalNotFound error: wait 15 seconds, then rerun the following until successful
$Retries = 0; While ($NewRole -eq $null -and $Retries -le 6) {
# Sleep here for a few seconds to allow the service principal application to become active (usually, it will take only a couple of seconds)
Sleep 15
New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $AzADApp.ApplicationId -ErrorAction SilentlyContinue
$NewRole = Get-AzRoleAssignment -ServicePrincipalName $AzADServicePrincipal.ApplicationId -ErrorAction SilentlyContinue
$Retries++;
}
"Application {0} Created Successfully" -f $AzADApp.DisplayName
# Display the values for your application
"Save these values for using them in your application"
"Subscription ID: {0}" -f (Get-AzContext).Subscription.SubscriptionId
"Tenant ID:{0}" -f (Get-AzContext).Tenant.TenantId
"Application ID:{0}" -f $AzADApp.ApplicationId
"Application AzADAppSecret :{0}" -f $AzADAppSecret
}
}
else {
"Application{0} Already Exists" -f $AzADApp.DisplayName
}
# Creating Azure Resource Group
$DataFactoryName = "xxxxx-DataFactory"
$ResourceGroupName = "xxxxx-ResourceGroup"
$ResourceGroup = Get-AzResourceGroup -Name $ResourceGroupName
$Location = 'westeurope'
if (-not $ResourceGroup) {
$ResourceGroup = New-AzResourceGroup $ResourceGroupName -location 'westeurope'
if ($ResourceGroup) {
"Resource Group {0} Created Successfully" -f $ResourceGroup.ResourceGroupName
}
else {
"ERROR: Resource Group Creation UNSUCCESSFUL"
}
}
else {
"Resource Group {0} Exists" -f $ResourceGroup.ResourceGroupName
}
# Creating Azure Data Factory
$DataFactory = Get-AzDataFactoryV2 -Name $DataFactoryName -ResourceGroupName $ResourceGroup.ResourceGroupName
if (-not $DataFactory) {
$DataFactory = Set-AzDataFactoryV2 -ResourceGroupName $ResourceGroup.ResourceGroupName -Location $ResourceGroup.Location -Name $DataFactoryName
if ($DataFactory) {
"Data Factory {0} Created Successfully" -f $DataFactory.DataFactoryName
}
else {
"ERROR: Data Factory Creation UNSUCCESSFUL"
}
}
else {
"Data Factory {0} Already Exists" -f $DataFactory.DataFactoryName
}
# Creating Azure SQL Server and Database
$ServerName = "xxxxx"
$DatabaseName = "xxxxx"
$AzSQLServer = Get-AzSqlServer -ServerName $ServerName
$Subscription = Get-AzSubscription
"Subscription Data" -f $Subscription.Id
if (-not $AzSQLServer) {
"Creating New Azure SQL Server"
$AdminSqlLogin = "xxxxx"
$Password = "xxxxx"
$StartIp = "xxxxx.xxxxx.xxxxx.xxxxx"
$EndIp = "xxxxx.xxxxx.xxxxx.xxxxx"
$AzSQLServer = New-AzSqlServer -ResourceGroupName $ResourceGroupName `
-ServerName $ServerName `
-Location $Location `
-SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminSqlLogin, $(ConvertTo-SecureString -String $Password -AsPlainText -Force))
if ($AzSQLServer) {
$FireWallRule = New-AzSqlServerFirewallRule -ResourceGroupName $ResourceGroupName `
-ServerName $ServerName `
-FirewallRuleName "AllowedIPs" -StartIpAddress $StartIp -EndIpAddress $EndIp
if ($FireWallRule) {
"Server Created Successfully {0} with firewall Rule Setup" -f $AzSQLServer.ServerName
}
else {
"Server Created Successfully {0} No FireWall Setup" -f $AzSQLServer.ServerName
}
}
else {
"ERROR: Server Creation UNSUCCESSFUL"
}
}
else {
"Server Exists {0}" -f $AzSQLServer.ServerName
}
$AzSQLDatabase = Get-AzSqlDatabase -DatabaseName $DatabaseName -ServerName $ServerName -ResourceGroupName $ResourceGroup.ResourceGroupName
if (-not $AzSQLDatabase) {
"Creating New Azure SQL Database"
$Parameters = #{
ResourceGroupName = $ResourceGroupName
ServerName = $ServerName
DatabaseName = $DatabaseName
RequestedServiceObjectiveName = 'S0'
}
$AzSQLDatabase = New-AzSqlDatabase #Parameters
if ($AzSQLDatabase) {
"Azure SQL Database {0} Created Successfully " -f $AzSQLDatabase.DatabaseName
}
else {
"ERROR: Azure SQL Database Creation UNSUCCESSFUL"
}
}
else {
"Database {0} Exists " -f $AzSQLDatabase.DatabaseName
}
You could use Clear-AzContext to remove all Azure credentials, account, and subscription information. Then use Connect-AzAccount -Tenant xxxxx -Subscription xxxxx, it should work.

Resources