You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PowerShell删除文本文件最后3行无效,求排查问题

PowerShell脚本删除文件最后3行无效果的问题排查

原文件内容

Apple=1
Manggo=1
Appleandmanggobellongsto=Jimmy
Apple=1
Manggo=1
Appleandmanggobellongsto=Dave
Apple=1
Manggo=1
Appleandmanggobellongsto=Carlton

期望结果

Apple=1
Manggo=1
Appleandmanggobellongsto=Jimmy
Apple=1
Manggo=1
Appleandmanggobellongsto=Dave

你的错误脚本

$File = c:\Text.txt
get-content $File | select-object -skiplast 3 | set-contect $File

错误点分析

  • 变量赋值错误:$File = c:\Text.txt 未给路径加引号,PowerShell会将c:\Text.txt解析为命令而非字符串路径,必须用单引号或双引号包裹路径:$File = 'c:\Text.txt'
  • 命令拼写错误:set-contect是拼写错误,正确命令为Set-Content(少了字母n)
  • 文件读写冲突:直接通过管道对同一个文件进行读写,会导致PowerShell在读取文件的同时尝试写入,引发文件锁定,最终导致写入失败

正确脚本示例

方法一:先读取内容到内存再写入

$File = 'c:\Text.txt'
$filteredContent = Get-Content $File | Select-Object -SkipLast 3
Set-Content $File -Value $filteredContent

方法二:用括号强制优先完成读操作

$File = 'c:\Text.txt'
(Get-Content $File | Select-Object -SkipLast 3) | Set-Content $File

内容的提问来源于stack exchange,提问作者DeGun999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 15:37:42