[英]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.