# This PS snippet is to create or update autonumber attribute.
# The User Name, Password and the Organization Name are to be updated before executing this.
Install-Module -Name Microsoft.Xrm.Data.Powershell -RequiredVersion 2.8.7 -Scope CurrentUser
$password = ConvertTo-SecureString "***" -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential("username@domain.com",$password)
$crmOrg = Get-CrmConnection -Credential $credentials -DeploymentRegion NorthAmerica -OnlineType Office365 -OrganizationName "dev-dev" -MaxCrmConnectionTimeOutMinutes 5
function CreateUpdateAutonumberAttribute {
param (
[Parameter(Position=0, Mandatory=$true)][string]$AttributeName,
[Parameter(Position=1, Mandatory=$true)][string]$AttributeDisplayname,
[Parameter(Position=2, Mandatory=$true)][string]$EntitySchemaname,
[Parameter(Position=3, Mandatory=$true)][string]$AutoNumberFormat,
[Parameter(Position=4, Mandatory=$true)][string]$Message
)
try{
Write-Output "Processing autonumber attribute $AttributeName ..."
$autonumattribute = New-Object Microsoft.Xrm.Sdk.Metadata.StringAttributeMetadata
$autonumattribute.SchemaName = $AttributeName
$autonumattribute.LogicalName = $AttributeName
$autonumattribute.DisplayName = New-Object Microsoft.Xrm.Sdk.Label($attributedisplayname,1033)
$autonumattribute.Format = [Microsoft.Xrm.Sdk.Metadata.StringFormat]::Text
$autonumattribute.MaxLength = 100
$autonumattribute.AutoNumberFormat = $AutoNumberFormat
if($message -eq 'create'){
$request = New-Object Microsoft.Xrm.Sdk.Messages.CreateAttributeRequest
}
elseif($message -eq 'update'){
$request = New-Object Microsoft.Xrm.Sdk.Messages.UpdateAttributeRequest
}
$request.Attribute = $autonumattribute
$request.EntityName = $EntitySchemaname
$response = $crmOrg.Execute($request)
Write-Output "... autonumber attribute $AttributeName Processed."
return $response
}
catch {
Write-Warning -Message $_.Exception.Message
}
}
CreateUpdateAutonumberAttribute -AttributeName 'accountnumber' -AttributeDisplayname 'Account Number' -EntitySchemaname 'account' -AutoNumberFormat '{DATETIMEUTC:yyyyMMddhhmmss}' -Message 'update'
No comments:
Post a Comment