Home > Back-end >  How to pass a powershell script to Windows PowerShell Host in C#?
How to pass a powershell script to Windows PowerShell Host in C#?

Time:12-02

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#.

My goal is pass my ps1 file that contains:

$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 

to a native implementation in C#. This return the CPU usage of a process. 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 ");

Do you have any idea how to transfer it to powershell Object and methods on C#?

CodePudding user response:

You can add parameters block (param()) to your script and invoke it:

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();
  • Related