繁体   English   中英

从 C# 应用程序运行 powershell 命令

[英]Run powershell command from C# application

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

Enter-PSSession –ComputerName fedsrv01.domain.local

Start-ADSyncSyncCycle -PolicyType Delta

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

https://learn.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它工作正常。

任何帮助将不胜感激。

干杯,

城野

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

来自 C# 的 Powershell 命令“该术语未被识别为 cmdlet”

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

城野

暂无
暂无

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

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