简体   繁体   English

通过c#执行powershell脚本会抛出“ <comment> 不被识别为cmdlet的名称”异常

[英]Executing powershell script through c# throws “<comment> is not recognized as the name of a cmdlet” exception

I am using .Net 4.6.1 for a Winform application. 我正在将.Net 4.6.1用于Winform应用程序。

I neet to execute some command to configure user settings through powershell. 我没有执行一些命令来通过Powershell配置用户设置。 The powershell reference that I used is under C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\WindowsPowerShell\\3.0 , so (I guess) its version is 3.0. 我使用的powershell引用位于C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\WindowsPowerShell\\3.0 ,因此(我想)其版本为3.0。

I use following to execute powershell command: 我使用以下命令执行powershell命令:

System.Management.Automation.PowerShell shell = System.Management.Automation.PowerShell.Create();
shell.AddScript("Get-LocalUser -Verbose");

then check 然后检查

shell.Streams.Error[0].Exception;

and see following error: 并看到以下错误:

The term 'Get-LocalUser' is not recognized as the name of a cmdlet, function, script file, or operable program. 术语“ Get-LocalUser”不能识别为cmdlet,函数,脚本文件或可运行程序的名称。 Check the spelling of the name, or if a path was included, verify that the path is correct and try again. 检查名称的拼写,或者是否包含路径,请验证路径是否正确,然后重试。

I also tried executing the command through a powershell file like: 我还尝试通过以下Powershell文件执行命令:

var psi = new ProcessStartInfo();
psi.CreateNoWindow = false;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.Verb = "runas";
psi.FileName = @"powershell.exe";
psi.Arguments = $" -File \"<path-to-file>\\MyScript.ps1\"";
try
    {
        Process proc = new Process();
        proc.StartInfo = psi;
        proc.Start();
        string f = proc.StandardError.ReadToEnd();
        proc.WaitForExit();
        exitCode = proc.ExitCode;
    }

But I got the same error. 但是我遇到了同样的错误。

How can I call a powershell script or powershell within c#? 如何在C#中调用Powershell脚本或Powershell?

EDIT: it turns out to be 32-64 bit issue. 编辑:原来是32-64位问题。 When I switched to x64, it worked just fine. 当我切换到x64时,它工作正常。

You should ensure you compile your C# code to target x64 (ie 64-bit) as most PowerShell modules will only work in 64-bit mode. 您应该确保将C#代码编译为以x64(即64位)为目标,因为大多数PowerShell模块只能在64位模式下工作。 If your C# code runs in 32-bit mode, it will invoke a 32-bit PowerShell environment, which will cause problems. 如果您的C#代码以32位模式运行,它将调用32位PowerShell环境,这将导致问题。

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

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