从c应用程序运行powershell

本文关键字:powershell 运行 应用程序 | 更新日期: 2023-09-27 18:24:25

你好,在powershell中有一个包含21行代码的文件。我需要一种用c#中的按钮运行这个文件的方法。我在Visual Studio 2010中使用c#。如果有实现的方法,请告诉我。

// 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();

例如,我需要按下一个按钮,使脚本发生

从c应用程序运行powershell

您可以使用Ingo Karstein 的PS2EXE

这将创建一个带有自己的powershell主机并嵌入脚本的c#可执行文件。

我有一个c#项目,它采用PS2EXE中的c#代码,增加了读取加密的powershell脚本内容、解密并运行它的能力。

一些对我有用的提示。我的应用程序已在中运行

  1. 使用管理员权限运行Visual Studio,这样可以避免Hkey_Local出现错误。。。

  2. 在powershell中,运行此getexecutionpolicy以查看策略并在setexecutionPolicy未注册的情况下设置未注册。这避免了操作系统的任何限制。

用上面写的代码,应用程序就可以工作了。准备好测试!!!