脚本手动运行,但不通过c#

脚本手动运行,但不通过c#,c#,powershell,windows-server-2012,C#,Powershell,Windows Server 2012,我编写了一个简单的控制台应用程序,该应用程序以管理员权限运行,代码基于,用户输入一个.ps1(powershell)脚本路径,应用程序执行此路径中的脚本 首先,我在“Hello World”脚本上尝试了该应用程序,它工作正常,但当我尝试其他脚本时,powershell会给出一个错误 我在.ps1scipt中有这个: install-WindowsFeature smtp-server Read-Host -Prompt “Press Enter to exit” 令人惊讶的是,如果我手动运行此

我编写了一个简单的控制台应用程序,该应用程序以管理员权限运行,代码基于,用户输入一个
.ps1
(powershell)脚本路径,应用程序执行此路径中的脚本

首先,我在“Hello World”脚本上尝试了该应用程序,它工作正常,但当我尝试其他脚本时,powershell会给出一个错误

我在
.ps1
scipt中有这个:

install-WindowsFeature smtp-server
Read-Host -Prompt “Press Enter to exit”
令人惊讶的是,如果我手动运行此命令
install windowsfeact smtp server
,它可以正常工作

但我需要的是,该应用程序可以做到这一点,而不是手动

以下是powershell错误:

install-WindowsFeature : The term 'install-WindowsFeature' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
At c:\users\administrator\desktop\EnableSMTP.ps1:1 char:1
+ install-WindowsFeature smtp-server
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (install-WindowsFeature:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Press Enter to exit:

我想你可能需要一个大写的“我”。。。
Install WindowsFeature

Install WindowsFeature是ServerManager模块提供的cmdlet。手动运行脚本时,必须已将此模块导入到会话中。通过程序运行时,不会导入模块,因此无法识别cmdlet名称。尝试添加
Import Module ServerManager
作为脚本的第一行,看看这是否解决了您的问题。

这在过去发生在我身上

在解决方案资源管理器中,右键单击项目-->属性-->生成

将平台目标从“任意CPU”更改为x64


在Windows资源管理器(文件夹)中,您能否找到您的exe,然后单击它以管理员身份运行?如果是的话,这样做有效吗?如果确实如此,则需要使用提升的权限运行此应用程序。这可能有助于我的应用程序以管理员身份运行,正如我在我的post@Flufy你在什么操作系统上运行这个?通常,这将在服务器操作系统上运行,您需要首先导入
ServerManager
。您可以在安装了RSAT工具的Win10上运行此操作。我在windows server上运行此操作2012@Flufy在
安装WindowsFeature
之前,请输入
导入模块ServerManager
Powershell不区分大小写模块名称可能有误;运行
Get命令Install windowsfeact |选择module
查看提供该cmdlet的模块名称。然后将导入模块添加到脚本中。