Dynamics CRM: PowerShell to create and disable contacts

For more info on managing identities in Dynamics CRM, see presentation on the MIM Usergroup .

I will jump right into it and just show the functions. If you want to see what files I need to reference in PowerShell and how to connect to CRM see my other blog post,

Dynamics 365/2016 CRM: Using PowerShell to Manage user Identity

Create Contact

function CreateContact($_firstName, $_lastName){
$contactId = $null;
try

{
#Create a new contact.
$contact = New-Object -TypeName Contact
$contact.FirstName = $_firstName
$contact.LastName = $_lastName
#$contact.OwnerId = $userId.ToEntityReference()
$contactId = $_service.Create($contact);
Write-Host
“Created a contact “
$contactId
“for”
$_lastName
$_firstName

}
# Catch any service fault exceptions that Microsoft Dynamics CRM throws.
catch

{
# You can handle an exception here or pass it back to the calling method.
Write-Host
$_.Exception.Message

}

}

Disable Contact

function DisableContact($_userId)
{
try
{
# The using statement assures that the service proxy is properly disposed.

# Retrieve a contact.
$query = New-Object -TypeName Microsoft.Xrm.Sdk.Query.ColumnSet
#$query.AddColumn(“Contact”);
$query.AddColumn(“firstname”);
$query.AddColumn(“lastname”);

$contact = $_service.Retrieve(“contact”,$_userId, $query);
if ($contact -ne $null)
{
Write-Host $user.LastName $user.FirstName ” contact is retrieved.”
$request = New-Object -TypeName Microsoft.Crm.Sdk.Messages.SetStateRequest
$request.EntityMoniker = $user.ToEntityReference()
$request.State = New-Object -TypeName Microsoft.Xrm.Sdk.OptionSetValue(1)
$request.Status = New-Object -TypeName Microsoft.Xrm.Sdk.OptionSetValue(-1)

$_service.Execute($request);

Write-Host “Contact is disabled.”
}
}
#Catch any service fault exceptions that Microsoft Dynamics CRM throws.
catch
{
#You can handle an exception here or pass it back to the calling method.
Write-Host $_.Exception.Message
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s