I wanted to automate dev/test environments lately in Azure and I faced the following issue...

Azure PowerShell cmdlets introduced in version 0.8.15 AzureProfile support:


AzureProfile:
New cmdlets to manage in-memory profiles

  • New-AzureProfile: Create a new in-memory Profile
  • Select-AzureProfile: Select the profile to be used in the current session

Added -Profile parameter to every cmdlet - the cmdlet will use the passed-in profile to authenticate with Azure


But I cannot get that to work like in this example, if I execute this script in a new PowerShell session, with valid credential, it fails the first time it run.

if(!$global:issueAzureCred) {
    $global:issueAzureCred = Get-Credential
}

Import-Module Azure

Clear-AzureProfile -Force
$random = Get-Random -Maximum 99999
$storageAccount = 'devtestpowershell{0}' -f $random
$subscriptionId = '{SubscriptionIdHere}'

$azureProfile = New-AzureProfile -SubscriptionId $subscriptionId -StorageAccount $storageAccount -Credential $global:issueAzureCred
Select-AzureProfile -Profile $azureProfile
New-AzureStorageAccount -StorageAccountName $storageAccount -Type Standard_LRS -Location 'East US 2' -Profile $azureProfile

Error:

New-AzureStorageAccount : Your Azure credentials have not been set up or have expired, please run Add-AzureAccount to set up your Azure credentials.
At C:\Users\someuser\Desktop\Add-AzureAccountIssue.ps1:15 char:1

New-AzureStorageAccount -StorageAccountName $storageAccount -Type Sta ...

CategoryInfo : NotSpecified: (:) [New-AzureStorageAccount], ArgumentException
FullyQualifiedErrorId : System.ArgumentException,Microsoft.WindowsAzure.Commands.ServiceManagement.StorageServices.NewAzureStorageAccountCommand

##Impacted versions
I tested the script on these version and always got the same behavior

* 0.8.15.1
* 0.8.16.0
* 0.9.0

##Workaround
if you perform the *New-AzureProfile* and *Select-AzureProfile* statements back to back it will solve the problem...

```
$azureProfile = New-AzureProfile -SubscriptionId $subscriptionId -StorageAccount $storageAccount -Credential $global:issueAzureCred
Select-AzureProfile -Profile $azureProfile

$azureProfile = New-AzureProfile -SubscriptionId $subscriptionId -StorageAccount $storageAccount -Credential $global:issueAzureCred
Select-AzureProfile -Profile $azureProfile

Get-AzureVMImage
```

OR you can still use *Select-AzureSubscription* with *Add-AzureAccount* or Management certificates with *Import-AzurePublishSettingsFile*

[I opened an issue on GitHub about this](https://github.com/Azure/azure-powershell/issues/362).