I have this code into which I load snapin (from MS Dynamics NAV in this case):
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
using (var ps = PowerShell.Create())
{
ps.Runspace = runspace;
ps.AddScript("Add-PSSnapin Microsoft.Dynamics.Nav.Management")
.AddScript("Get-NAVServerInstance");
var output = ps.Invoke();
}
}
This code works when I use the AddScript method, as shown in the code. But why does the AddCommand method not work (see Comment)? It seems that snapin is not loaded, because the error indicates that the Get-NAVServerInstance cmdlet is unknown. How should this work?
I know that I can create a working environment with InitialSessionState, on which I imported snapin. Then ps.AddCommand ("Get-NAVServerInstance") works. But when I want to create a remote working session (using WSManConnectionInfo), I cannot find a way to create an initialSessionState.
UPDATE:
, , AddCommand , ( ) . InitialSessionState RunspaceConfiguration RunspaceFactory.CreateRunspace(...). , :
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-NAVServerInstance");
var output = ps.Invoke();
}
}
, WSManConnectionInfo.
, snapin ( )? ?