I am using .Net 4.6.1 for a Winform application.
I neet to execute some command to configure user settings through 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.
I use following to execute powershell command:
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. 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:
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#?
EDIT: it turns out to be 32-64 bit issue. When I switched to x64, it worked just fine.
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. If your C# code runs in 32-bit mode, it will invoke a 32-bit PowerShell environment, which will cause problems.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.