简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM