我想在 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 物件和方法嗎?
uj5u.com熱心網友回復:
您可以將引數塊 ( param())添加到腳本中并呼叫它:
const string script = @"
param(
[string] $ProcessName,
[string] $Path
)
$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";
PowerShell powerShellCommand = PowerShell.Create();
powerShellCommand
.AddScript(script)
.AddParameters(new PSPrimitiveDictionary
{
{ "ProcessName", "Notepad" },
{ "Path", @"D:\FolderName\data.txt" }
})
.Invoke();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/371002.html
