Question

I'm writing some powershell cmdlets to automate the configuration of Azure subscriptions. One of the use-cases is having a developer configure their own environment. Currently this takes about 20 steps and is error-prone. Handing them some default azure cmdlets would end up with more mistakes than using Microsoft's Azure GUI and a set of instructions. I want a script that will hold their hand through the configuration process, and abstract away a lot of bookkeeping and error-checking.

I tried doing all this in a Powershell script, but that gets messy:

Function SelectSubscription()
    {
    $match = $False;
    while(!($match))
        {
        Write-Host "Enter a subscription from the following list:";
        DisplaySubscriptions;
        $global:subscription = Read-Host " ";

        (Get-AzureSubscription).GetEnumerator() | ForEach-Object
            {
            if ($_.SubscriptionName -eq $subscription)
                {
                Write-Host "Setting default subscription to: $subscription";
                Set-AzureSubscription -DefaultSubscription $subscription;
                $match = $True;
                };
            };
        if (!($match))
            {
            Write-Host "That does not match an available subscription.`n";
            };
        };
    }

(This displays the current subscriptions you can see with your .publishsettings file and prompts you to select from among them. If your input is invalid, it asks again.)

What I'd like is a custom cmdlet like Set-MyAzureSubscription that will have all this logic in it. And later I can hook it up to Get-Help.

So I'm set up in VS2010 to make cmdlets, and I want to call Get-AzureSubscription from inside a custom cmdlet. I can call cmdlets by opening an instance of a powershell script... and then pasting text in programmatically... but that seems less than ideal.

More on that approach here: Call azure powershell cmdlet from c# application fails

Is there another way of doing this? This is what I have so far in C#.

namespace Automated_Deployment_Cmdlets
{
 [Cmdlet(VerbsCommon.Set, "CustomSubscription", SupportsShouldProcess=true)]
 class CustomSubscription : PSCmdlet
    {
      [Parameter(Mandatory=true, ValueFromPipelineByPropertyName=true)]
      public string DefaultSubscription { get; set; }

     protected override void ProcessRecord()
     {
         base.ProcessRecord();
         // Call Get-AzureSubscription, then do some stuff -- as above.
      }
 }
}
Was it helpful?

Solution

This MSDN topic shows how you can easily call another cmdlet from within your C# cmdlet implementation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top