【问题标题】:How to run PowerShell comands in C#如何在 C# 中运行 PowerShell 命令
【发布时间】:2021-12-16 20:12:09
【问题描述】:

在 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# 执行所有这些操作会更容易?
  • 我想通过这种方式来做:D

标签: c# powershell command


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你可以使用这个命令来执行powershell脚本

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

    【讨论】:

      猜你喜欢
      • 2021-01-08
      • 2011-03-02
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2014-09-16
      相关资源
      最近更新 更多