c# - 如何在 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();
}
解决方案
而不是 AddCommand,我必须使用 AddScript 方法。
推荐阅读
- excel - 时间范围内的分钟数 - EXCEL
- python - 正则表达式匹配多个前缀,解压到列
- wpf - Slider (itemsControl) 不会更改 Int 数组中的值
- python - 无法使用 subplot 命令组合绘图
- python - 有 2 个字典,我想附加第二个字典中的匹配键并将它们作为列表 f 字典存储在父字典中
- sql-server - T-SQL MERGE 不会按预期处理 NULL
- sql-server - ogr2ogr 不创建表
- ios - JSONMedel 库中的模型级联不起作用
- reactjs - 在本机反应中获取轮播中的动态图像
- node.js - Rich Embed 中的 Discord.js 标记通道