[英]How to run PowerShell comands in C#
在 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();
}
而不是 AddCommand,我必须使用 AddScript 方法。
您可以使用此命令执行 powershell 脚本
PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"D:\PSScripts\MyScript.ps1")).Invoke();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.