通过C#执行Powershell脚本会引发“ <comment>无法识别为cmdlet的名称”异常

时间:2019-05-17 12:43:10

标签: c# .net powershell

我正在将.Net 4.6.1用于Winform应用程序。

我不太想执行一些命令来通过Powershell配置用户设置。 我使用的powershell参考在C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0下,因此(我想)它的版本是3.0。

我使用以下命令执行powershell命令:

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

然后检查

shell.Streams.Error[0].Exception;

,然后看到以下错误:

  

术语“ Get-LocalUser”不能识别为cmdlet,函数,脚本文件或可运行程序的名称。检查名称的拼写,或者是否包含路径,请确认路径正确,然后重试。

我还尝试通过以下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;
    }

但是我遇到了同样的错误。

如何在C#中调用Powershell脚本或Powershell?

编辑:结果是32-64位问题。当我切换到x64时,它工作正常。

2 个答案:

答案 0 :(得分:3)

您应该确保将C#代码编译为目标x64(即64位),因为大多数PowerShell模块只能在64位模式下运行。如果您的C#代码以32位模式运行,它将调用32位PowerShell环境,这将导致问题。

答案 1 :(得分:1)

我也有过类似的经历,只是在改变了ExecutionPolicy之后才成功。错误是相同的,但所有细节似乎都很好。

PS 7.1.3,Microsoft.Powershell.SDK。

使用这个:

PowerShell.Create().AddCommand("Set-ExecutionPolicy")
            .AddParameter("-ExecutionPolicy", "Bypass")
            .Invoke();

在使用 PowerShell 执行任何操作之前运行此代码一次。