[英]Executing PowerShell Script with Invoke-SqlCmd cmdlet from C#
[英]Executing powershell script through c# throws “<comment> is not recognized as the name of a cmdlet” exception
我正在将.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时,它工作正常。
您应该确保将C#代码编译为以x64(即64位)为目标,因为大多数PowerShell模块只能在64位模式下工作。 如果您的C#代码以32位模式运行,它将调用32位PowerShell环境,这将导致问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.