【发布时间】:2022-01-08 08:49:36
【问题描述】:
我想在 C# 项目(.NETFramework)上使用Windows PowerShell Host 的方法 我在我的项目中安装了 System.Management.Automation.dll 以在 C# 上运行 PowerShell 的命令。
我的目标是传递我的 ps1 文件,其中包含:
$ProcessName = "Notepad"
$Path = "D:\FolderName\data.txt"
$CpuCores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors
$Samples = (Get-Counter "\Process($Processname*)\% Processor Time").CounterSamples
$Samples | Select @{Name="CPU %";Expression={[Decimal]::Round(($_.CookedValue / $CpuCores), 2)}} | Out-File -FilePath $Path -Append
到 C# 中的本机实现。这将返回进程的 CPU 使用率。 我想使用 PowerShell 对象来避免拥有 ps1 文件,因为我想使用 System.Management.Automation.PowerShell 类在 C# 上编写前面的命令,例如:
PowerShell powerShellCommand = PowerShell.Create();
powerShellCommand.AddCommand("Get-WMIObject");
powerShellCommand.AddArgument("Win32_ComputerSystem");
powerShellCommand.AddArgument("NumberOfLogicalProcessors ");
你知道如何将它转移到 C# 上的 powershell 对象和方法吗?
【问题讨论】:
-
我不确定我是否理解您要执行的操作。你有一个 ps 文件。您想读取文件并使用 PowerShell api/Object 从文件中提取一行并执行它 - 对吗?
-
无需通过API重新创建脚本语句,直接调用脚本即可:
powerShellCommand.AddScript(@"C:\path\to\script.ps1");
标签: c# powershell