The ‘Set-AzContext’ command was found in the module ‘Az.Accounts’ but the module could not be loaded.

In this Azure tutorial, we will discuss how to fix the error, The ‘Set-AzContext’ command was found in the module ‘Az. Accounts, but the module could not be loaded. which comes while trying to create an Azure SQL database using PowerShell in Azure.

The ‘Set-AzContext’ command was found in the module ‘Az.Accounts’, but the module could not be loaded.

Recently while trying to create an Azure SQL database using PowerShell, I got the above error message. Below is the cmdlet I was executing for creating the AzureSQL database.

Note: This is the part of my actual script.

$MysubscriptionId = '1cdf4300-dee5-4518-9c9c-feaa72a5cbd1'
# Set subscription details
Set-AzContext -SubscriptionId $MysubscriptionId 
The 'Set-AzContext' command was found in the module 'Az.Accounts'

The exact error message is

Set-AzContext: The ‘Set-AzContext’ command was found in the module ‘Az. Accounts, but the module could not be loaded. For more information, run ‘Import-Module Az. Accounts’.
At line:19 char:1

  • Set-AzContext -SubscriptionId $MysubscriptionId
  • ~~~~~
    • CategoryInfo : ObjectNotFound: (Set-AzContext: String) [], CommandNotFoundException
    • FullyQualifiedErrorId: CouldNotAutoloadMatchingModule

The ‘Set-AzContext’ command was found in the module ‘Az.Accounts’, but the module could not be loaded. [Solved]

To fix the above issue, you need to follow the below steps

1. Run the below command to import the Az. Accounts

C:\windows\system32> Import-Module Az.Accounts
The 'Set-AzContext' command was found in the module 'Az.Accounts'

After executing the above command, there might be a chance you will get one error like Import-Module: File C:\Program Files\WindowsPowerShell\Modules\Azure\5.3.0\.psm1 cannot be loaded because running scripts is disabled on this system.

2. Now run the below command to set the Execution policy to fix this issue

PS C:\windows\system32> Set-ExecutionPolicy RemoteSigned
The 'Set-AzContext' command was found

3. Click on the yes button from the below popup.

How to fix The 'Set-AzContext' command was found

4. Now run the below command again to import the Az.Accounts

C:\windows\system32> Import-Module Az.Accounts
Set-AzContext Fails to Set Context to named Subscription

5. Now, run the cmdlet again for creating the AzureSQL database(This is part of my script), you will not get any error this time.

$MysubscriptionId = '1cdf4300-dee5-4518-9c9c-feaa72a5cbd1'
# Set subscription details
Set-AzContext -SubscriptionId $MysubscriptionId 
The 'Set-AzContext' command was found in the module

You may like the following Azure tutorials:

Conclusion

In this Azure tutorial, we discussed how to fix the error, The ‘Set-AzContext’ command was found in the module ‘Az. Accounts’. I hope it helped you to fix your issue.