This is part 2 of the mini-series on PowerShell for Dynamics 365 CE. If you haven’t read the first part, it’s available HERE.
In this part we’re looking at connecting to a D365 environment.
Just like we did with the first part, we’re putting the connection code in a function. We’re doing this in order to be able to call it multiple times, depending on the environment we’re connecting to. Eventually, we’ll connect to both a source and a target environments.
The function looks like this:
# Function to establish the connection to CRM environments
function GetCRMConn{
param(
[string]$user,
[string]$secpasswd,
[string]$crmUrl
)
Write-Host “UserId: $user CRM URL: $crmUrl”
$secpasswd2 = ConvertTo-SecureString -String $secpasswd -AsPlainText -Force
Write-Host “Creating Credentials…”
$myCreds = New-Object System.Management.Automation.PSCredential ($user, $secpasswd2)
Write-Host “Credentials object created…”
$crm = Connect-CrmOnline -Credential $myCreds -ServerUrl $crmUrl
return $crm
}
Again, the lines starting with a “#” are comment lines.
We start in our function by defining the parameters we’ll be passing to our function. We have here the user name, password and URL to the environment we connect to.
The first line is using Write-Host to print back to the console the user name and the URL to your D365 instance. We’re leaving out the password on purpose.
The next line converts the password from a string to a secure string. We need this in order to create the credentials object. Details on ConvertTo-SecureString are available at:
After another output to console we create the credentials object by calling New-Object.
Documentation is available at:
With New-Object we can create various object types. In our case, we are looking to create a PSCredential object. The command takes parameters for user name and password. The details are available at:
Finally, with the credentials object, and after another output line to console, we can create the connection to our instance. We call Connect-CrmOnline to create the connection object, passing the credentials object and the URL to the instance we connect to. The function return the connection object.
You call this function using the following command:
$myCRM = GetCRMConn –user “username” –secpasswd “password” –crmURL “url”
And that’s that. Next post looks at extracting a solution from your D365 instance.
Cheers!