Monday, October 1, 2012

Use Powershell to increment build on AX 2012 Model


I have been working on a new version of my PowerShell script I use to export models to disk. I wanted to increment the build number each time a model was exported, so I started with my export script and added a single method and hooking things up.

The PowerShell method looks like this:

Function Update-Version ([string]$model, [string]$server, [string]$database, [int]$incrementBuildBy)
{
 $manifest = Get-AXModelManifest -Server $server -Database $database -Model $model
 $manifestVersion = $manifest.Version
 $manifestVersionSplit = $manifestVersion.Split('.')
 $manifestVersionSplit[3] = $incrementBuildBy + $manifestVersionSplit[3]
 $ofs = "."
 $versionStr = [string] $manifestVersionSplit
 $manifestVersion = "Version=" + $versionStr
 Edit-AXModelManifest -Server $server -Database $database -Model $model -ManifestProperty $manifestVersion
 return $manifest
}

Given this method I changed my export to look more like this:

$backupFilePath = New-BackupFolder($axBackupFolder)
$models = Get-AXModel -Server $server -Database $database

foreach ($model in $models)
{
 $backupFileName = ""
 $elementCount  = ""
 $nameToBackup  = $model.Name.ToString()
 $layer    = $model.Layer.ToString()
 $elementCount  = $model.ElementCount.ToString() 
 $versionStr  = $model.Version.ToString()
 $backupFileName = $backupFilePath + "\" + $nameToBackup + ".axmodel"    
 
 if ($layer.ToUpper().Contains($layerFilter.ToUpper()) -and $nameToBackup.ToUpper().Contains($modelFilter.ToUpper()))
 {
  Update-Version $nameToBackup $server $database $incrementBuildBy 
  $backupFileName = $backupFilePath + "\" + $nameToBackup + "_" + $versionStr + ".axmodel"
  "Exporting " + $elementCount + " elements from " + $nameToBackup + "..."
  File-Backup $nameToBackup $backupFileName $server $database
 }
 else
 {
  "Skipping " + $backupFileName + " in layer " + $layer
 }
}
"Completed!"

The two other utility methods are simply like this:

Function New-BackUpFolder([string]$destinationFolder)
{
 $dte = get-date
 $dte = $dte.tostring() -replace "[:\s/]", "."
 $backUpPath = "$destinationFolder" + $dte
 $null = New-Item -path $backUpPath -itemType directory
 return $backUpPath
}

Function File-Backup([string]$model, [string]$fileName, [string]$server, [string]$database)
{
 Export-AXModel -Model $model -File $fileName -Server $server -Database $database
}

So in order to wrap things up, all you need is to declare at the top a few variables:
$server = "mydbserver"
$database = "MicrosoftDynamicsAx"
$axBackupFolder = "c:\axModelBackup\"
$modelFilter = "AwesomeApp"
$layerFilter = "ISV"
$incrementBuildBy = 1

And that's a wrap!

1 comment:

  1. Great Post. Need your advice. In my current project, i am seeing two models created with the same name and when i try to get rid of one of them, it throws an error saying more than one model with the same name. Any idea?

    ReplyDelete