question

TimDayLtColCAP-6557 avatar image
0 Votes"
TimDayLtColCAP-6557 asked PeterStam-9052 edited

New-AzStorageContext conflict with Connect-ExchangeOnline

In an Azure Function App, when New-AzStorageContext is run after Connect-ExchangeOnline, Azure throws this error:

 The 'New-AzStorageContext' command was found in the module 'Az.Storage', but the module could not be loaded. For more information, run 'Import-Module Az.Storage'.

However, New-AzStorageContext completes successfully if it is run before Connect-ExchangeOnline. Anyone know why this is happening?

Code in profile.ps1

 function New-StorageContext {
     if( -not $global:CAPWATCHStorageContext) {
    
         # must be global so it persists across functions
         $global:CAPWATCHStorageContext = New-AzStorageContext -StorageAccountName  $env:Z_WM_CAPWATCH_STORAGE_ACCOUNT -UseConnectedAccount;
         Write-Host "Created global CAPWATCH Storage Context";
     } else {
         Write-Host "Found global CAPWATCH storage context: $($global:CAPWATCHStorageContext.Name)";
     }
 }

 function Connect-ExchangeOnlineSession {
     [CmdletBinding()]
     Param (
         [array] $CommandsToLoad = ($env:Z_WM_EXO_COMMANDS -split ','),
         [switch] $Force,
         [switch] $SuppresErrorNotify
     )
    
     try {
         if (-not $Force.IsPresent){ #if Force flag set than disregard
             # Check for existing connection
             try {
                 $null = Get-EXOMailbox -ResultSize 1;
                 return; #connected so don't need to run this function
             } catch {
                 # Not connected, proceed
             }
         }        
         # Connect to Exchange Online
         if (-not $global:cert) {
    
             # No certificate found so we'll retrieve it.
             # connecting to Key Vault based on connected AzAccount and managed identity with permissions on Key Vault
             $tCert = Get-AzKeyVaultSecret -VaultName $env:Z_WM_KEYVAULT_NAME -Name $env:Z_WM_EXO_CERT_NAME -AsPlainText;
             $tCert = [System.Convert]::FromBase64String($tCert);    
                
             # store in global var so we don't have to retrieve it again
             $global:cert = New-Object -TypeName X509Certificate2 -ArgumentList $tCert, $null, MachineKeySet;            
         }
         $pssOptions = New-PSSessionOption -IdleTimeout 300000 -NoMachineProfile;
         $tSplat = @{
             AppId                       = $env:Z_WM_EXO_APP_ID;
             Certificate                 = $global:cert;
             Organization                = $env:Z_WM_ORGANIZATION;
             CommandName                 = $CommandsToLoad;
             PSSessionOption             = $PssOptions;
             ShowProgress                = $false;
             ShowBanner                  = $false; 
         }
         $null = Connect-ExchangeOnline @tSplat -ErrorAction Stop;                                        
            
         # Connected to Exchange Online V2         
         return;
     } catch {        
         Write-Host "Error connecting to Exchange Online: $_";
         <# if (-not $SuppresErrorNotify.IsPresent) {
             Send-Email  -Type Error `
                         -Subject "[Provision] [Process] Error connecting to Exchange Online" `
                         -Subtitle "$_" `
                         -Body "**Error message**<br />$($_.Exception.ToString() -replace "`n",'<br/>')";
         } #>
         throw;
     }
 }

requirements.psd1

 # This file enables modules to be automatically managed by the Functions service.
 # See https://aka.ms/functionsmanageddependency for additional information.
 #
 @{
     # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. 
     #'Az' = '5.*';
     'Az.Accounts' = '2.*';
     'Az.KeyVault' = '3.*';
     'Az.Storage' = '3.*';
     'SqlServer' = '21.*';
     'ExchangeOnlineManagement' = '2.0.6-Preview5';
     #'MicrosoftTeams' = '1.1.7-preview';
     #'Microsoft.Graph' = '1.*' 
     #'Logging' = '4.*';
     #'AzureADPreview' = '2.*';
     #'ExchangeOnlineManagement' = '2.0.4-Preview6';
     #'ExchangeOnlineManagement' = '2.0.4';
 }

run.ps1 (swap the order of these commands to duplicate)

     New-StorageContext;
     Connect-ExchangeOnlineSession;






office-exchange-online-itproazure-functionsazure-storage-accounts
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@TimDayLtColCAP-6557 , Can you move the script from profile.ps1 to run.ps1 and test? Only startup script should be placed in profile.ps1

0 Votes 0 ·

Hi,
Same here, after using Connect-ExchangeOnline none of the Az.Storage cmdlets seems to work anymore. Not all Az cmdlets have this problem e.g. Get-AzResource works. Also after Disconnect-ExchangeOnline, when importing Az.Storage im getting:

import-module Az.Storage
Import-Module: Assembly with same name is already loaded

Looks like a runspace issue or something. Any updates?
Regards,
Peter

0 Votes 0 ·

0 Answers