【问题标题】:Run powershell command from C# application从 C# 应用程序运行 powershell 命令
【发布时间】:2019-04-30 19:58:50
【问题描述】:

我想从我的 C# 应用程序中运行以下 powershell 命令:

Enter-PSSession –ComputerName fedsrv01.domain.local

Start-ADSyncSyncCycle -PolicyType Delta

我找到了一些有关 Powershell 类的信息,但由于缺乏经验而难以实现我想要的。

https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.powershell?redirectedfrom=MSDN&view=pscore-6.2.0

这是我目前所拥有的:

我已经添加了程序集并引用了 system.management.automation

using (var powershell = PowerShell.Create())
{

     //powershell.AddCommand("get-process");
     powershell.AddCommand("Enter-PSSession -ComputerName fedsrv01.domain.local");


     powershell.Invoke();
}

我收到一条错误消息,'The term 'Enter-PSSession -ComputerName fedsrv01.domain.local' is not recognized as the name of a cmdlet, function, script file, or operable program.

如果我使用:powershell.AddCommand("get-process"),它执行得很好。

如果我在同一台 PC 上启动 Powershell 并输入,Enter-PSSession -ComputerName fedsrv01.domain.local 它工作正常。

任何帮助将不胜感激。

干杯,

乔诺

【问题讨论】:

标签: c# powershell


【解决方案1】:

尝试将您的应用程序编译为 x64。如果编译为 x86 平台,那么它将使用虚拟化的 System32 目录,因此您需要的功能可能不存在。

Powershell commands from C# 'the term is not recognizes as cmdlet'

【讨论】:

    【解决方案2】:

    好的,在对 PowerShell 类进行了更多研究之后,我现在意识到您必须使用 .addparameter 方法单独添加参数。 .addcommand 仅适用于 PowerShell 命令。现在,为什么我得到错误说找不到命令是有道理的。它假设整个字符串是一个命令。 问题解决了!

    乔诺

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      相关资源
      最近更新 更多