I have now tried about a hundred ways of automating the execution of powershell scripts from C# and Dynamics NAV 2013.
Running the script works 100% from either Powershell ISE or executing it with the following command in commandline:
powershell.exe -version 3.0 -command ". 'C:\temp\script.ps1'"
So the last option I tried now was to put this all in a .bat file and execute the .bat file using System.Diagnostics.Process (also, executing the .bat file manually works 100%)
Setup.GET;
ProcessInfo := ProcessInfo.ProcessStartInfo(FileName); //The .bat File
ProcessInfo.UseShellExecute := FALSE;
ProcessInfo.RedirectStandardError := TRUE;
//<< Credentials
ProcessInfo.Domain := Setup.Domain;
ProcessInfo.UserName := Setup.Username;
SecurePwd := SecurePwd.SecureString();
FOR i := 1 TO STRLEN(Setup.Password) DO
SecurePwd.AppendChar(Setup.Password[i]);
ProcessInfo.Password := SecurePwd;
//>> Credentials
Process := Process.Start(ProcessInfo);
StreamReader := Process.StandardError();
MESSAGE(StreamReader.ReadToEnd());
Without setting the credentials I get as output from the message:
The handle is invalid.
The handle is invalid.
The handle is invalid.
The handle is invalid.
The handle is invalid.
Set-ExecutionPolicy : Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.
And it just about complains about something on every line in the script.
Import-Module : The specified module 'D:\psmodules\Multitenancy\NAVMultitenancySamples.psm1' was not loaded because no valid module file was found in any module directory.
etc. etc.
With the credentials filled in, message is blank but it didn't do anything that it was supposed to.
Now, from the message I can see that it is trying to access the registry entries for Powershell version 1 instead of 3... could that be part of the problem? Version 3 is installed:
PS C:\> $Host.Version
Major Minor Build Revision
----- ----- ----- --------
3 0 -1 -1