MegaCoolServiceScritps.psm1

Function CreateResourceGroupIfNotPresent([string]$ResourceGroupName, [string]$ResourceGroupLocation) {
    $resourceGroup = Get-AzureRmResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue
    if(!$resourceGroup) {
        Write-Host "Creating resource group '$ResourceGroupName' in location '$ResourceGroupLocation'";
        New-AzureRmResourceGroup -Name $ResourceGroupName -Location $ResourceGroupLocation
    } else {
        Write-Host "Using existing resource group '$ResourceGroupName'";
    }
}

function DeployTemplate([string]$ResourceGroupName, [string]$TemplateFile, [Hashtable]$TemplateParameters, [switch]$ValidateOnly) {
    if ($ValidateOnly) {
        $ErrorMessages = Format-ValidationOutput (Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName `
                                        -TemplateFile $TemplateFile `
                                        @TemplateParameters)

       if ($ErrorMessages) {
            Write-Output '', 'Validation returned the following errors:', @($ErrorMessages), '', 'Template is invalid.'
        }
        else {
            Write-Output '', 'Template is valid.'
        }
    }
    else {
        New-AzureRmResourceGroupDeployment -Name ((Get-ChildItem $TemplateFile).BaseName + '-' + ((Get-Date).ToUniversalTime()).ToString('MMdd-HHmm')) `
                                           -ResourceGroupName $ResourceGroupName `
                                           -TemplateFile $TemplateFile `
                                           @TemplateParameters `
                                           -Force -Verbose `
                                           -ErrorVariable ErrorMessages
        if ($ErrorMessages) {
            Write-Output '', 'Template deployment returned the following errors:', @(@($ErrorMessages) | ForEach-Object { $_.Exception.Message.TrimEnd("`r`n") })
        }
    }
}

export-modulemember -function CreateResourceGroupIfNotPresent
export-modulemember -function DeployTemplate