web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :

Using C# classes on your NAV Powershell tasks

Stefano Demiliani Profile Picture Stefano Demiliani 37,166 Most Valuable Professional

After yesterday’s post about scheduling Microsoft Dynamics NAV tasks in parallel with Powershell, I’ve received an interesting question: If I have a custom C# DLL that works with NAV (calls a NAV web service for example) can I also use this DLL on my script?

The answer is YES. In a Powershell script you can also embed your C# code or also use your external C# DLLs. Let’s see a quick example:

PowershellDLL_01

In this Powershell script, we’ve added a reference to an external C# DLL and then we’ve added a C# code (MyNAVSuperClass). I’ve created this sample class with two methods, one static and one not static.

After the C# class, the Add-Type Powershell command adds a reference to the external DLL (type):

PowershellDLL_02.jpgThen, the C# class is istantiated:

PowershellDLL_03.jpg

and now we call the C# methods from Powershell (here you can see how to call a static method and how to call a non-static method):

PowershellDLL_04.jpg

The complete script is as follows:

$Assem = (
 "EID.NavTools, Version=2.0.0.0, Culture=neutral, PublicKeyToken=73e9bde131e8729c"
 )

$code = @" 
using System;
using EID.NavTools;

namespace EID 
{ 
 public class MyNAVSuperClass 
 { 
   public static void MyStaticMethod() 
   { 
     EID.NavTools NAVTools = new EID.NavTools();
     NavTools.PerformNAVTask(); 
     Console.WriteLine("Working with NAV"); 
   }
 
   public void MyMethod() 
   { 
     Console.WriteLine("Working with NAV 2"); 
   } 
  } 
} 
"@

Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp

if (-not ([System.Management.Automation.PSTypeName]'EID.MyNAVSuperClass').Type) 
{ 
 Add-Type -TypeDefinition $code -Language CSharp; 
}

[EID.MyNAVSuperClass]::MyStaticMethod();

$instance = New-Object EID.MyNAVSuperClass; 
$instance.MyMethod();

 


This was originally posted here.

Comments

*This post is locked for comments