简体   繁体   English

从 C# 在 powershell 中运行 RemoteDesktop commandlet 时出错

[英]Error while running RemoteDesktop commandlets in powershell from C#

I have tried executing RemoteDesktop commandlets in powershell using C#.我曾尝试使用 C# 在 powershell 中执行 RemoteDesktop commandlet。

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.当我调用命令时,它会给出错误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 ?如何实现调用 RemoteDesktop 命令行开关?

I solved this.我解决了这个问题。 I change run mode to x64 from Any CPU.我将运行模式从任何 CPU 更改为 x64。

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.using块的开头应该可以解决您的问题。

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 .默认InitialSessionState仅加载核心命令行开关,并且ExecutionPolicy设置为最严格的: Microsoft.PowerShell.ExecutionPolicy.Default

To work around this, I had to set the ExecutionPolicy as shown below :为了解决这个问题,我必须设置ExecutionPolicy ,如下所示:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM