Home > Enterprise >  How to run PowerShell comands in C#
How to run PowerShell comands in C#

Time:11-04

In cmd I write this and it works (this command removes N first lines from file):

powershell.exe
$file = "C:\Test\file.txt"
$content = Get-Content $file
$content[10..($content.length-1)]|Out-File $file -Force

I want to write this code on C# but my way isn't correct. Can you explain why?

using (PowerShell ps = PowerShell.Create())
{
  ps.AddCommand($"$file = \"{fullPathToTxt}\"")
  .AddCommand("$content = Get-Content $file")
  .AddCommand($"$content[{numLine}..($content.length-1)]|Out-File $file -Force")
  .Invoke();
}

CodePudding user response:

Instead of AddCommand, i have to use AddScript method.

CodePudding user response:

You can use this command for execute powershell script

PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"D:\PSScripts\MyScript.ps1")).Invoke();
  • Related