Swimburger

PowerShell snippet: Get optionset value/labels from Dynamics CRM Entity/Attribute

Niels Swimberghe

Niels Swimberghe - - Dynamics

Follow me on Twitter, buy me a coffee

CRM and PowerShell logo

Instead of having to use the CRM interface to copy all the labels and values manually, you can save yourself a lot of time using this PowerShell script.
Using the following script file named "GetOptionSet.ps1", you can list all the value/label pairs for a given Entity + OptionSet-Attribute:

Param(
    [Parameter(Mandatory=$true)]
    [String]
    $ConnectionString,
    [Parameter(Mandatory=$true)]
    [String]
    $EntityLogicalName,
    [Parameter(Mandatory=$true)]
    [String]
    $OptionSetAttributeName
)

# Import the Dynamics XRM PowerShell module
# https://www.powershellgallery.com/packages/Microsoft.Xrm.Tooling.CrmConnector.PowerShell/3.3.0.887
Import-Module Microsoft.Xrm.Tooling.CrmConnector.PowerShell;
# Get a CrmServiceClient to communicate with Dynamics CRM
$CrmClient = Get-CrmConnection -ConnectionString $ConnectionString;

# Create a RetrieveAttributeRequest to fetch Attribute metadata
$AttributeRequest = [Microsoft.Xrm.Sdk.Messages.RetrieveAttributeRequest]::new();
$AttributeRequest.EntityLogicalName = $EntityLogicalName;
$AttributeRequest.LogicalName = $OptionSetAttributeName;
$AttributeRequest.RetrieveAsIfPublished = $True;
$AttributeResponse = [Microsoft.Xrm.Sdk.Messages.RetrieveAttributeResponse]$CrmClient.Execute($AttributeRequest);

# Get the Value/Label pairs and print them to the console
$AttributeResponse.AttributeMetadata.OptionSet.Options `
    | Select-Object -Property `
        @{Name = "Value"; Expression={$_.Value}},`
        @{Name = "Label"; Expression={$_.Label.UserLocalizedLabel.Label}};

# Close the connection to CRM
$CrmClient.Dispose();

To use the script,

# Follow the link below to learn how to create your connectionstring:
# https://docs.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/xrm-tooling/use-connection-strings-xrm-tooling-connect#connection-string-parameters
$CrmConnectionString = "YOURCONNECTIONSTRING";

.\GetOptionSet.ps1 `
    -ConnectionString $CrmConnectionString `
    -EntityLogicalName "lead" `
    -OptionSetAttributeName "statuscode";

# Output will look something like this:
#   Value Label
#   ----- -----
#       1 New
#       2 Contacted
#       3 Qualified
#       6 Not Interested
#       5 Unable to Contact

 

Related Posts

Related Posts