0

I have tried executing RemoteDesktop commandlets in powershell using C#.

The following is my program :

static void Main(string[] args)
        {
            using (var powershell = PowerShell.Create())
            {
                powershell.Commands.AddCommand("Import-Module").AddArgument("remotedesktop");
                powershell.Invoke();
                powershell.Commands.Clear();
                powershell.AddCommand(@"Get-RDRemoteApp");
                powershell.AddCommand(@"out-string");
                foreach (var result in powershell.Invoke())
                {
                    Console.WriteLine(result);
                }
            }
        }

When I invoke command it gives the error System.Management.Automation.CommandNotFoundException: The term 'Get-RDRemoteApp' is not recognized as the name of a cmdlet, function, script file, or operable program.

How can I achieve calling RemoteDesktop commandlets ?

I solved this. I change run mode to x64 from Any CPU.

Mashiro
  • 7
  • 3
  • Is this module installed and available for the user you run the C# code in? You may try importing the module using its complete path to the folder containing the module. – Theo Jul 09 '18 at 11:16
  • Yes, This module is installed. When I import this module using powershell console, No error reported – Mashiro Jul 10 '18 at 00:28

1 Answers1

1

You need to set a persistent runspace for all of your commands. The way your code is now, each command is being executed in it's own isolated runspace. Adding the following code:

var runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
powershell.Runspace = runspace;

to the beginning of the using block should fix your problem.

Bruce Payette
  • 2,251
  • 7
  • 8