Learn NAV PowerShell in your coffee breaks


For learning PowerShell in the lunch break we have this option.

We thought that was a good idea. But we also thought we can do even better: Do some NAV PowerShell in your coffee breaks. This post is the first in a series of small script ideas of things you can do with NAV using PowerShell. If you find this useful or have ideas to improvements then please add your comments below and also suggest what you would like to see next.

 

Coffee Break 1: Add AD users to NAV.

User story

Consider the following scenario: With the new security model in Microsoft Dynamics NAV 2013 and later versions, it is no longer possible to add users and permissions by merely adding Windows Groups. Besides, as of NAV 2013, you may not be using Windows authentication. The user wants to automate what is otherwise a trivial task of looking up Windows users, and entering them into NAV.
 
The script below will give some ideas for adding NAV users in a batch.

Pre requisites:

Depending on which OS you run it on, you may need to install Remote Server Administration Tools (RSAT). Make sure to install the one that matches your OS and version. If you run Win 8.1 then install it from here:

Remote Server Administration Tools for Windows 8.1
http://www.microsoft.com/en-gb/download/details.aspx?id=39296

If you run it on a server OS, you may just need to enable it. For more details:
https://technet.microsoft.com/en-us/library/dd378937(v=ws.10).aspx

To see if the module is installed, just try to import it and see if that works:

Import-Module ActiveDirectory

 

 Coffee break 1 – importing NAV users from Active Directory

#Suggestion: Run each line below one by one and then put them together as needed.

#Install Remote Server Administration Tools (RSAT) first as described above, then import module

Import-Module ActiveDirectory

 

#Import NAV admin module for the version of Dynamics NAV you are using

Import-Module ‘C:\Program Files\Microsoft Dynamics NAV\80\Service\NavAdminTool.ps1’

 

#Specify your Dynamics NAV Service name

$NavServerName = “DynamicsNAV80”

 

#AD filter for use in the next line. If you are not on a large domain, then run the next line (get-aduser) without this filter, or if you use the filter then adjust it to your scenario and domain.

$Mysearchbase = “DC=<Domain>[,DC=<Corp Domain>,…]”

#For example:

$Mysearchbase = “DC=EUROPE,DC=CONTOSO,DC=com”

 

#Next we will get AD users. If you want to import only users from a Windows group or a subdomain, you can filter the result set on sub-domain/group/…  Furthermore, we have chosen to retrieve only user name and alias in the example below, but choose any properties that fit your purpose. You can see the entire cmdlet output by running get-help <cmdletname>.Furthermore, we want to save this output into a list that we later can retrieve and modify if needed. The list format and default delimiter might vary depending on regional settings, a semicolon is defined here as a delimiter.

get-aduser -filter ‘samaccountname -like “*bill*”‘ -searchbase $Mysearchbase | Select-Object -Property Name,SAmaccountname | export-csv “c:\temp\userlist.csv” –notypeinformation  -Delimiter ‘;’ -force 

#Assign the list to a variable

$myuserlist = Import-csv “c:\temp\userlist.csv”

#Show the list

$myuserlist

 

#Another way of assigning the output to a variable is using outvariable. Next we want to  then pipe everything to New-NAVServerUser cmdlet to create new users in NAV. In the above example we have only read SamAccountName and User Name from  AD, so to add users as Windows users to NAV, following our Contoso scenario, we need to add the domain name too : DOMAIN\samaccountname. 

import-csv C:\temp\userlist.csv -Delimiter ‘;’ -OutVariable myuserlist | foreach {New-NAVServerUser -serverinstance $NavServerName -WindowsAccount “<DOMAIN>\$($_.samaccountname)}

#You can combine the above two actions (Reading AD users and then importing them into NAV) into one cmdlet, without saving the output as in the example above.

#We’re using a loop here and not the pipeline, as New-NAVServerUser doesn’t seem to take the pipeline input

get-aduser -filter ‘samaccountname -like “*bill*”‘ -searchbase $Mysearchbase | foreach { New-NAVServerUser -serverinstance $NavServerName -WindowsAccount “<DOMAIN>$($_.samaccountname)}

 

<#Consider now the following scenario. User wants to get AD users using the export script above, but wants to add roles to this user list, before importing them into NAV. So he will break the above process into 2 steps again – in step 1 he will save AD users into a list, then assuming a modified list with added roles – he will import the list of users and their roles into NAV in step 2.

Step one is then unchanged from the example above (using csv list). Next we will assume that the list is now modified to add roles to users.

Example below shows step 2, where this list is imported to create users and assign permissions in NAV. Userlist2.csv file refered to in the script below is the name of the csv file containing users and permissions. Example below shows format of this file (csv, semicolon delimited) with Contoso users as examples:

 

EUROPE\mrhill;BASIC,RAPIDSTART

EUROPE\mssaddow;BASIC,COST,CASHFLOW

EUROPE\joeroberts;SUPER

 

If a user or a role defined in this list already exists in NAV, the cmdlet is expected to continue since the ErrorAction parameter is set to Continue (which is also the default value of this parameter). However it is singled out here to direct the attention to error handling opportunities that best fit the user’s scenario. Review the possible values of this parameter and how to use them using get-help cmdlet. The following blog is worth checking:

http://blogs.msdn.com/b/powershell/archive/2006/11/03/erroraction-and-errorvariable.aspx

#>

 

$NavServerName =“DynamicsNAV80”

$list = Import-csv -Path C:\temp\userlist2.csv -Delimiter ‘;’ -Header username,roleset

foreach ($user in $list)

{

  $navuser=Get-NAVServerUser -ServerInstance $NavServerName

   if(!($navuser.UserName -contains $user.username))

     { 

    New-NAVServerUser -ServerInstance $NavServerName -WindowsAccount $user.username -ErrorAction Continue

    }

#In the csv file used in this example, the list of roles is divided by a comma

  $roleset=$user.roleset.Split(‘,’)

     foreach ($role in $roleset)

    {

    $navrole=Get-NAVServerUserPermissionSet -ServerInstance $NavServerName -WindowsAccount $user.username

    if(!($navrole.PermissionSetID -contains $role))

        {

     New-NAVServerUserPermissionSet -ServerInstance $NavServerName -WindowsAccount $user.username -PermissionSetId $role -ErrorAction Continue

 

       }

    }

}

 

 

More coffee breaks to follow soon!

 

Jasminka Thunes, Escalation Engineer Dynamics NAV EMEA

Lars Lohndorf-Larsen, Escalation Engineer Dynamics NAV EMEA

 

 

ImportUsersExample.zip

Comments (8)

  1. Pallea says:

    GREAT Examples 🙂

    I use this one for SQL-backup all the time

    # MM = month, HH= 24hour, hh= 12hour format.

    $timer = (Get-Date -Format yyyyMMdd-HHmm)

    $filename = "C:BACKUP" + $timer + "_NAV_SQLBACKUP"

    $Databasename = "Demo Database NAV (8-0)"

    $SQLServername = "WINDOWS81NAVDEMO"

    MD C:BACKUP

    Push-Location

    Import-Module sqlps -Verbose

    # Push is neccesary in order to be able to "exit" the SQLSERVER-mode

    # You could do it like this…

    #Backup-SqlDatabase -Database "Demo Database NAV (8-0)" -ServerInstance WINDOWS81NAVDEMO -BackupAction Database -backupfile "C:backupSQLBACKUP" -initialize -verbose

    /# but heyy… use some variables instead…

    Backup-SqlDatabase -Database $Databasename -ServerInstance $SQLServername -BackupAction Database -backupfile $filename -initialize -verbose

    # remember to POP-out of the SQLSERVER-mode

    pop-location

    have fun 🙂

    Palle

  2. Hi Pallea,

    Thanks a lot for your comments. Great to hear that you like the examples. And thanks for sharing PowerShell – just what we want to see :-). Funny enough the next post we are planning also includes backups…

  3. nutcracker says:

    thank you for your posting

    I just want to ask.

    If I want to specify the license type in user card, what should I do?

    thank you again.

  4. Hi Nutcracker,

    What if you write this in PowerShell?

    New-NAVServerUser DynamicsNAV80 -LicenseType Full

    For me, I even get intellisense showing what options are available (I always use the ISE environment, not the dos-prompt-lookalike shells!).

  5. Pallea says:

    I also allways use Powershell ISE. And what I do is that I create a file called profile.ps1

    This file only contains one line:

    Import-Module "C:Program FilesMicrosoft Dynamics NAV80ServiceMicrosoft.Dynamics.Nav.Management.dll" -Verbose

    The file is saved in the folder

    C:WindowsSystem32WindowsPowerShellv1.0

    Then all the powershell scripts are loaded at every Powershell-start regardless of ISE or not.

    Palle

  6. nutcracker says:

    hi Lars Lohndorf-Larsen

    thank you very much.

    but I seems that I can not use -LicenseType parameter in Nav 2013.

  7. Hi Nutcracker,

    NAV Admin tool can only manage versions 7.1 and higher.

    But LicenseType parameter should work fine in NAV 2013 R2.

  8. nutcracker says:

    Hi Jasminka Thunes

    I see,thank you very much.

Skip to main content