首页 > 解决方案 > 如何在 C# 中运行 PowerShell 命令

问题描述

在 cmd 我写这个并且它有效(这个命令从文件中删除 N 第一行):

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

我想在 C# 上编写这段代码,但我的方式不正确。你能解释一下为什么吗?

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

标签: c#powershellcommand

解决方案


而不是 AddCommand,我必须使用 AddScript 方法。


推荐阅读