[英]Run powershell scripts from c#
我正在嘗試在我的應用程序中使用C#編寫Powershell腳本。 問題是,如果我使用c#運行腳本,腳本將無法完成任務,但是如果我手動運行,則腳本將能夠完成任務。
那是腳本: DISM /online /Enable-Feature /Featurename:NetFx3 /All
該腳本在Windows服務器上啟用Framwork 3.5。 資源
我的代碼:
NuGet: System.Management.Automation
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("DISM /online /Enable-Feature /Featurename:NetFx3 /All ");
// begin invoke execution on the pipeline
IAsyncResult result = PowerShellInstance.BeginInvoke();
// do something else until execution has completed.
// this could be sleep/wait, or perhaps some other work
while (result.IsCompleted == false)
{
Console.WriteLine("Waiting for pipeline to finish...");
Thread.Sleep(1000);
// might want to place a timeout here...
}
Console.WriteLine("Finished!");
}
我用這里的例子
注意:我的應用程序以管理員身份運行。
嘗試在您的Powershell腳本中添加管理員權限,有時會有所幫助
PowerShell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -windowstyle hidden -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -noexit -File "$ScriptPath"' -Verb RunAs}"
您可以將powershell命令保存在ps1文件中,並將路徑作為參數($ ScriptPath)給出。 通過運行指定的代碼,可以在C#上測試此powershell命令。 希望這可以幫助。 如果不是,那么我建議使用C#System.Diagnostics命名空間中的Process。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.