PowerShell Trick: Azure Cloud Service access Custom Settings

MSDN documentation to Add Custom settings to use in Azure Cloud Service shows an example to access the custom setting via C#.

But this can very well be done via PowerShell too.

Following the above MSDN link, let's suppose that you have added a custom setting like below:

http://1.bp.blogspot.com/-6gaPpv2BhX4/VZ9hXSQz8BI/AAAAAAAABwI/SZXQBcLQa7o/s1600/CustomSetting.png

One can simply append the below code in the ConfigureCloudService.ps1 which gets executed by a startup task on a web or worker role.

Below is the sample code to get started:


TRY {
    # search for the Dll
    Write-Verbose -Message "Creating credential object"
    $Splathashtable = @{
                        'Path' = "$env:windir\Microsoft.NET\assembly\";
                        'Filter' = 'Microsoft.WindowsAzure.ServiceRuntime.dll';
                        'Include' = '*.dll'
                        }
    $dllfile = Get-ChildItem @Splathashtable -Recurse  | Select-Object -Last 1 # selecting only one object, in case of multiple results
    Write-Verbose -Message "ServiceRuntime dll found"
     
    # add the DLL to the current PowerShell session
    Add-Type -Path $dllfile.FullName   
    Write-Verbose -Message "ServiceRuntime dll added to the current runspace"
  
    # Call the Static method on the class to retrieve the setting value
    $Setting = [Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment]::GetConfigurationSettingValue('TestKey')
    Write-Verbose -Message "Fetched TestKey from the Service Configuration"
  
    # Now use the value as you please
    Write-Verbose -Message "Value stored in TestKey is $Setting"
}
CATCH {
    throw $_.exception
  
}

Recently needed to configure roles on the cloud service based on the custom settings in a Python project so followed this simple trick.

Want to read more on the topic, visit the link below:
PowerShell + Azure + Python: Use Project Custom settings