![](/img/trans.png)
[英]How to call Powershell script and pass parameters from C# windows form
[英]How to pass a powershell script to Windows PowerShell Host in C#?
I would like to use the methods of Windows PowerShell Host on C# project (.NETFramework) I had installed System.Management.Automation.dll on my project to run the commands of PowerShell on C#.
我的目标是传递我的 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 使用率。 I want to use the PowerShell Object to avoid to have the ps1 file, because I want to write the previous commands on C# using the System.Management.Automation.PowerShell class, example:
PowerShell powerShellCommand = PowerShell.Create();
powerShellCommand.AddCommand("Get-WMIObject");
powerShellCommand.AddArgument("Win32_ComputerSystem");
powerShellCommand.AddArgument("NumberOfLogicalProcessors ");
您知道如何将其转移到 powershell Object 和 C# 上的方法吗?
您可以将参数块( 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.