Creating a stand-alone windows console app with the following code (C#) works well ... but not in a .Net application.
private void getNavTenantPs1()
{
InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] { "C:\\Program Files\\Microsoft Dynamics NAV\\80\\Service\\NavAdminTool.ps1" });
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.Commands.AddCommand("Get-NAVTenant");
ps.Commands.AddParameter("-ServerInstance", "ModifiedDatabase");
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(result.Properties["DatabaseServer"].Value);
}
}
or using this code
private void getNavTenantMgt()
{
var config = RunspaceConfiguration.Create();
PSSnapInException warning;
config.AddPSSnapIn("Microsoft.Dynamics.Nav.Management", out warning);
using (Runspace runspace = RunspaceFactory.CreateRunspace(config))
{
runspace.Open();
using (var ps = PowerShell.Create())
{
ps.Runspace = runspace;
ps.AddCommand("Get-NAVTenant");
ps.AddParameter("-ServerInstance", "ModifiedDatabase");
Collection<PSObject> results = ps.Invoke();
foreach (PSObject obj in results)
{
Console.WriteLine(obj.Properties["DatabaseServer"].Value);
}
}
}
}
But when I try and use the exact same code (either function above) in a Web Application such as an API or even just from an ASP.NET program the code does not work. The errors I receive are as follows
Error received when using getNavTenantPs1()
"An exception of type 'System.Management.Automation.CommandNotFoundException' occurred in System.Management.Automation.dll but was not handled in user code
Additional information: The term 'Get-NAVTenant' is not recognized as the name of a cmdlet, function, script file, or operable program..."
Error received when using getNavTenantMgt()
"An exception of type 'System.Management.Automation.PSArgumentException' occurred in System.Management.Automation.dll but was not handled in user code
Additional information: The Windows PowerShell snap-in 'Microsoft.Dynamics.Nav.Management' is not installed on this computer."
Does anyone have any idea why this is so? As said it works fine in a console but not in the .Net environment.
I just don't get it. ](*,) Maybe user impersonation or privileges when trying execute the NavAdminTool.ps1 file?
Any hints would be very welcome and appreciated!
0