Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
BizTalk Evaluation One Touch Configuration in Windows Azure
#
# Module manifest for module 'BizTalk.Management.Automation'
#
# Generated by: jdevillard
#
# Generated on: 30/04/2013
#
@{
# Script module or binary module file associated with this manifest.
# RootModule = ''
# Version number of this module.
ModuleVersion = '1.0'
# ID used to uniquely identify this module
GUID = '3f4d1966-a449-4e10-bcca-b18179586731'
# Author of this module
Author = 'jdevillard'
# Company or vendor of this module
CompanyName = 'Unknown'
# Copyright statement for this module
Copyright = '(c) 2013 jdevillard. All rights reserved.'
# Description of the functionality provided by this module
# Description = ''
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of the .NET Framework required by this module
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
NestedModules = @(
'BizTalk.Management.Automation.psm1'
)
# Functions to export from this module
FunctionsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*'
# List of all modules packaged with this module.
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess
# PrivateData = ''
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
#Wait Process
function Wait-AzureVMStatus{
[CmdLetBinding()]
param(
[string] $vmName,
[string] $status,
[int] $timeout = 5000
)
BEGIN{
$startTime = [System.DateTime]::UtcNow
$lastStatus;
}
PROCESS{
while($true)
{
$vmStatus = Get-AzureVM |? { $_.ServiceName -eq $vmName }
if($vmStatus.Status -eq $status){
Write-Host "$(Get-Date) $($vmName) has reached the status $($status)"
Write-Output $vmStatus.Status
break
}
Write-Host "$(Get-Date): Pending... $($vmName) has the status $($vmStatus.Status)"
Start-Sleep -s 5
if($startTime.AddMilliseconds($timeout) -lt [System.DateTime]::UtcNow){
Write-Host "$(Get-Date): Timeout Exceed... $($vmName) has the status $($vmStatus.Status)"
Write-Output $vmStatus.Status
break
}
}
}
END {}
}
function Download-File{
[CmdLetBinding()]
param(
[string] $fileName,
[string] $httpUrl
)
BEGIN{
#if not FullPath
#All File Are downloaded to AppData Folder
if(![System.IO.Path]::IsPathRooted($fileName))
{
$fileName = [System.IO.Path]::Combine("$($env:APPDATA)", $fileName);
}
}
PROCESS{
"Downloading $httpUrl"
$uri = New-Object "System.Uri" "$httpUrl"
$request = [System.Net.HttpWebRequest]::Create($uri)
$request.set_Timeout(15000) #15 second timeout
$response = $request.GetResponse()
if([System.Math]::Floor($response.get_ContentLength()/1024) -ne 0)
{
$totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)
}
else{ #less than 1K
$totalLength = $response.get_ContentLength()
}
$responseStream = $response.GetResponseStream()
$targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList $fileName, Create
$buffer = new-object byte[] 10KB
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $count
while ($count -gt 0)
{
$targetStream.Write($buffer, 0, $count)
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $downloadedBytes + $count
Write-Progress -activity "Downloading file '$($httpUrl.split('/') | Select -Last 1)'" -status "Downloaded ($([System.Math]::Floor($downloadedBytes/1024))K of $($totalLength)K): " -PercentComplete ((([System.Math]::Floor($downloadedBytes/1024)) / $totalLength) * 100)
}
}
END{
Write-Progress -activity "Finished downloading file '$($httpUrl.split('/') | Select -Last 1)'"
Write-Host "File Downloaded $($httpUrl) to $($fileName)"
$targetStream.Flush()
$targetStream.Close()
$targetStream.Dispose()
$responseStream.Dispose()
}
}
function create-account
{
[CmdLetBinding()]
param(
[string]$accountName,
[string]$accountDescription,
[string]$password
)
$hostname = hostname
$comp = [adsi]"WinNT://$hostname"
$user = $comp.Create("User", $accountName)
$user.SetPassword($password)
$user.SetInfo()
$user.description = $accountDescription
$user.SetInfo()
#$User.UserFlags[0] = $User.UserFlags[0] -bor 0×10000 #ADS_UF_DONT_EXPIRE_PASSWD flag is 0×10000
#$user.SetInfo()
$objOU = [ADSI]"WinNT://$hostname/Administrators,group"
$objOU.add(WinNT://$hostname/$accountName)
}
function Configure-BizTalk
{
[CmdLetBinding()]
param(
[string] $BizTalkConfigurationFilePath,
[string] $BizTalkMachineName,
[string] $BizTalkAppAccount,
[string] $BizTalkAppPassword,
[string] $OutputPath
)
BEGIN{
if(![System.IO.Path]::IsPathRooted($BizTalkConfigurationFilePath))
{
$BizTalkConfigurationFilePath = [System.IO.Path]::Combine($env:APPDATA,$BizTalkConfigurationFilePath)
}
[xml]$xmlConfigurationFile = Get-Content $BizTalkConfigurationFilePath
}
PROCESS{
#Change Server Name
$xmlConfigurationFile.SelectNodes("//*[local-name()='Server']") | % { if(! [String]::IsNullOrEmpty($_.InnerXml)){$_.InnerXml = $BizTalkMachineName } }
#Change UserName BizTalk App
$xmlConfigurationFile.SelectNodes("//*[local-name()='NTService'][UserName!='']") | % {
if($_.UserName.StartsWith("."))
{
$_.UserName = ".\$($BizTalkAppAccount)"
}
else
{
$_.UserName = $BizTalkAppAccount
}
$_.Password = $BizTalkAppPassword
}
}
END{
if($OutputPath -ne $null)
{
if(![System.IO.Path]::IsPathRooted($OutputPath))
{
$OutputPath = [System.IO.Path]::Combine($env:APPDATA,$OutputPath)
}
$xmlConfigurationFile.Save($OutputPath);
}
else
{
Write-Output $xmlConfigurationFile
}
}
}
function Configure-BizTalkConfigurationTask
{
[CmdLetBinding()]
param(
[string] $BizTalkConfigurationTaskFilePath,
[string] $BizTalkMachineName,
[string] $AdminUserAccount,
[string] $OutputPath
)
BEGIN{
if(![System.IO.Path]::IsPathRooted($BizTalkConfigurationTaskFilePath))
{
$BizTalkConfigurationTaskFilePath = [System.IO.Path]::Combine($env:APPDATA,$BizTalkConfigurationTaskFilePath)
}
[xml]$xmlTaskConfigurationFile = Get-Content $BizTalkConfigurationTaskFilePath
}
PROCESS{
#Change UserId
$xmlTaskConfigurationFile.Task.Principals.Principal.UserId = "$($BizTalkMachineName)\$($AdminUserAccount)"
#change CommandLine Argument
$xmlTaskConfigurationFile.Task.Actions.Exec.Arguments = "/s $($env:APPDATA)\BizTalkConfiguration.xml /l $($env:APPDATA)\BizTalkConfigurationLog.xml /ExtLog"
}
END{
if($OutputPath -ne $null)
{
if(![System.IO.Path]::IsPathRooted($OutputPath))
{
$OutputPath = [System.IO.Path]::Combine($env:APPDATA,$OutputPath)
}
$xmlTaskConfigurationFile.Save($OutputPath);
}
else
{
Write-Output $xmlTaskConfigurationFile
}
}
}
#Set-ExecutionPolicy unrestricted
Import-Module BizTalk.Management.Automation
###########################################
#Azure Subscription Configuration
###########################################
$subName = '<Subscription Name>'
$subId = '<Subscription Id>'
$vmStorageAccount = '<Vm Storage Account -- or Default storage account of your subscription>'
$cert = Get-Item Cert:\CurrentUser\My\<Certificate Thumbprint>
###########################################
#VM Configuration
###########################################
$vmName = '<Virtual Machine Name>';
$adminUserName = '<Virtual Machine Admin Account>'
$adminPassword = '<Virtual Mahcine Admin Password>'
###########################################
#BizTalk Configuration
###########################################
$BizTalkAppAccount = "<BizTalk Application User Account>"
$BizTalkAppPassword = "<BizTalk Application User Password>"
###########################################
#Beginning of the script
###########################################
Write-Host "-------- Start Of Script --------"
$startTimeDate = Get-Date;
Write-host "Configuring Azure Subscription"
Set-AzureSubscription -SubscriptionName $subName -SubscriptionId $subid -Certificate $cert
$storageAccount = Get-AzureStorageAccount -StorageAccountName $vmstorageAccount
Set-AzureSubscription -SubscriptionName $subName -SubscriptionId $subid -Certificate $cert -CurrentStorageAccount $vmStorageAccount
Write-Host 'Creating Virtual Machine'
$azureQuickVMResult = New-AzureQuickVM -Windows -ServiceName $vmName `
-name $vmName `
-ImageName "2cdc6229df6344129ee553dd3499f0d3__BizTalk-Server-2013-Evaluation" `
-EnableWinRMHttp -Location "West Europe" `
-AdminUsername $adminUserName `
-Password $adminPassword `
-InstanceSize Small
if($azureQuickVMResult.OperationStatus -ne 'Succeeded')
{
Write-Host 'Error Creating the VM'
return
}
#Wait for the Ready Role Status of the Virtual Machine
$result = Wait-AzureVMStatus -vmName $vmName -status 'ReadyRole' -timeout 800000
if($result -eq 'ReadyRole'){
Write-Host 'VM Successfully started'
$secpasswd = ConvertTo-SecureString $adminPassword -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($adminUserName, $secpasswd)
Write-host "Get Azure Windows Remote Uri"
$winRmConfiguration = Get-AzureWinRMUri $vmName;
Write-host "Create Session to Virtual Machine"
$pssessionOption = New-PSSessionOption -SkipCACheck
$mysession = New-PSSession -ComputerName "$($vmName).cloudapp.net" -Credential $mycreds -Port $winRmConfiguration.Port -UseSSL -Verbose -SessionOption $pssessionOption
Write-Host "Creating BizTalk User"
#Create User
Invoke-Command -ScriptBlock ${function:create-account} -ArgumentList $BizTalkAppAccount,$BizTalkAppAccount,$BizTalkAppPassword -Session $mysession
Write-Host "Downloading BizTalk Configuration Template and Transformation"
Invoke-Command -Session $mysession -Script ${function:Download-File} -argumentlist "BizTalkConfigurationDefaultAll.xml","https://jdevillard.blob.core.windows.net/biztalk/VMProvisioning/BizTalkConfigurationDefaultAll.xml"
Invoke-Command -Session $mysession -Script ${function:configure-BizTalk} -ArgumentList "BizTalkConfigurationDefaultAll.xml", $vmName,$BizTalkAppAccount,$BizTalkAppPassword, "BizTalkConfiguration.xml"
#Create BackupSSO folder
Write-Host "Creating Backup SSO Folder"
Invoke-Command -Session $mysession -ScriptBlock { New-Item c:\BackupSSO -type directory }
#Download Schedule Task Template File
Write-Host "Download Schedule Task Template File and Transformation"
Invoke-Command -ScriptBlock ${function:Download-File} -argumentlist "ScheduleTaskTemplate.xml","https://jdevillard.blob.core.windows.net/biztalk/VMProvisioning/ScheduleTaskTemplate.xml" -Session $mysession
invoke-command -session $mysession -script ${function:Configure-BizTalkConfigurationTask} -argumentlist "ScheduleTaskTemplate.xml",$vmName, $adminUserName, "ScheduleTask.xml"
#Create Schedule Task
Write-Host "Creating the Schedule task"
invoke-command -session $mysession -script {param($computerName, $userName, $password) . schtasks.exe /create /tn "BizTalk Configuration Task " /xml "$($env:APPDATA)\ScheduleTask.xml" /RU "$($computerName)\$($userName)" /RP $password} -Args $vmName,$adminUserName,$adminPassword
#Download ExtendedConfiguration
Write-Host "Downloading ExtendedConfiguration from Blob Storage"
Invoke-Command -ScriptBlock ${function:Download-File} -argumentlist "C:\Program Files (x86)\Microsoft BizTalk Server 2013\ExtendedConfiguration.exe","https://jdevillard.blob.core.windows.net/biztalk/ExtendedConfiguration/ExtendedConfiguration.exe" -Session $mysession
Invoke-Command -ScriptBlock ${function:Download-File} -argumentlist "C:\Program Files (x86)\Microsoft BizTalk Server 2013\ExtendedConfiguration.exe.config","https://jdevillard.blob.core.windows.net/biztalk/ExtendedConfiguration/ExtendedConfiguration.exe.config" -Session $mysession
#execute Schedule Task
Write-Host "Running Configuration"
invoke-command -session $mysession -script {param() . schtasks.exe /run /tn "BizTalk Configuration Task "}
#wait for end, reading file
Write-Host "Waiting for File Log"
Start-Sleep -s 10
Invoke-Command -session $mysession -ScriptBlock {Get-Content "C:\Program Files (x86)\Microsoft BizTalk Server 2013\ExtendedConfiguration.log" -Wait | ForEach-Object { if($_.StartsWith("End Of Program")){break}else{$_}}}
##For further use of the platform ;)
Write-Host "Downloading BizTalk Provider Powershell http://psbiztalk.codeplex.com"
#Download-File -httpUrl "http://download-codeplex.sec.s-msft.com/Download/Release?ProjectName=psbiztalk&DownloadId=276965&FileTime=129737326236800000&Build=20442" -fileName "C:\Users\jdevillard\Downloads\psbiztalk.msi"
Invoke-Command -ScriptBlock ${function:Download-File} -argumentlist "psbiztalk.msi","http://jdevillard.blob.core.windows.net/biztalk/BizTalkFactory%20PowerShell%20Provider%201.2.0.4.msi" -Session $mysession
Write-Host "Installing BizTalk Provider Powershell"
Invoke-Command -ScriptBlock {
Push-Location $env:APPDATA; . msiexec.exe /i "$($env:APPDATA)\psbiztalk.msi" /quiet /l* log.txt; Pop-Location
} -Session $mysession
#Next --- Need to be in x86 mode to use the Powershell Provider
#end of the scripts -- Total time
$endDateTime = Get-Date
$scriptDuration = $endDateTime.Subtract($startTimeDate)
Write-Host "-------- End Of Script --------"
Write-Host "Total Script Duration : $($scriptDuration.Hours):$($scriptDuration.Minutes):$($scriptDuration.Seconds)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment