你好有一個包含21個代碼的文件在power shell中。我需要一種方法來在c#中使用按鈕來運行此文件。我在Visual Studio 2010中使用c#。請讓我知道是否有辦法實現。從c#應用程序運行powershell
// Powershell
$Proc = Get-Process | Sort-Object CPU -Descending
$cores = Get-WmiObject Win32_processor
$memory = Get-WmiObject Win32_OperatingSystem
$Total = 10
$num = 1
Clear-Content c:\scripts\prueba.txt
foreach ($objItm in $Proc) {
If ($num -gt $Total) {
break #break the loop
}
[string] $strID=[System.Convert]::ToString($objItm.ID)
[string] $strProcessName=[System.Convert]::ToString($objItm.ProcessName)
[string] $strCPU=[System.Convert]::ToString($objItm.CPU)
[string] $strNUM=[System.Convert]::ToString($num)
$info=$strNUM+"-"+$strID+"-"+$strProcessName+"-"+$strCPU
$num += 1
$info|Add-Content c://scripts/prueba.txt
}
//Code c#
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(scriptFile)
Execute PowerShell script results = pipeline.Invoke();
我需要例如按下一個按鈕,使腳本發生
是的,有一種方法可以實現這一點。你有什麼嘗試,你做了多少研究? – alroc
那麼我一直在尋找並找到一種方式'RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); 流水線pipeline = runspace.CreatePipeline(); pipeline.Commands.Add(scriptFile); //執行PowerShell腳本 results = pipeline.Invoke();' –
但使用我的sp位置並且不起作用。我不知道還需要什麼,因爲第一個答案中的代碼已經在powershell中測試過並且工作完美 –