1

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

2
  • I'm not sure I understand what you're trying to do. You have a ps file. You'd like to read the file and use the PowerShell api/Object to take a line from the file and execute it - is that correct? Commented Dec 1, 2021 at 19:28
  • No need to recreate the script statements with the API, just invoke the script directly: powerShellCommand.AddScript(@"C:\path\to\script.ps1"); Commented Dec 1, 2021 at 19:31

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Giorgi!, this is what I was looking for! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.