【问题标题】:How to pass a powershell script to Windows PowerShell Host in C#?如何在 C# 中将 powershell 脚本传递给 Windows PowerShell 主机?
【发布时间】: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


【解决方案1】:

您可以在脚本中添加参数块 (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();

【讨论】:

  • 非常感谢 Giorgi!这就是我要找的东西! :)
猜你喜欢
  • 2015-06-07
  • 2011-08-01
  • 2020-09-04
  • 2012-05-05
  • 2021-12-05
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多