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.

2
  • 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. Commented Jul 9, 2018 at 11:16
  • Yes, This module is installed. When I import this module using powershell console, No error reported Commented Jul 10, 2018 at 0:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

I faced the same issue and found your post.

Default InitialSessionState only loads Core commandlets and ExecutionPolicy is set to the most restrictive: Microsoft.PowerShell.ExecutionPolicy.Default.

To work around this, I had to set the ExecutionPolicy as shown below :

InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
iss.ImportPSModule("RemoteDesktop");

PowerShell powershell = PowerShell.Create(iss);
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.