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

如何避免PowerShell脚本按内容删除文件时误删自身

解决Terragrunt生成文件删除脚本误删自身的问题

核心思路

通过获取当前脚本的绝对路径,在文件筛选阶段直接排除自身,不受脚本名称、存储路径变更的影响。

修正后的脚本

# 获取当前脚本的绝对路径
$currentScriptPath = $MyInvocation.MyCommand.Path

# 遍历文件 → 排除自身 → 匹配Terragrunt生成标记 → 获取文件路径 → 删除文件
Get-ChildItem -Recurse | 
  Where-Object { $_.FullName -ne $currentScriptPath } |
  Select-String "Generated by Terragrunt" -List |
  Select-Object -ExpandProperty Path |
  Remove-Item

关键细节说明

  • $MyInvocation.MyCommand.Path:PowerShell内置变量,能准确获取当前执行脚本的绝对路径,不管脚本改名或移动位置都有效。
  • Where-Object { $_.FullName -ne $currentScriptPath }:在遍历文件的第一步就排除脚本自身,避免后续匹配到脚本内容。
  • -ExpandProperty Path:修正原脚本的小问题,确保传给Remove-Item的是纯文件路径,而非带属性的对象。

安全预览技巧

如果不确定要删除的文件是否正确,可以先添加-WhatIf参数预览操作,不会实际删除文件:

$currentScriptPath = $MyInvocation.MyCommand.Path
Get-ChildItem -Recurse | 
  Where-Object { $_.FullName -ne $currentScriptPath } |
  Select-String "Generated by Terragrunt" -List |
  Select-Object -ExpandProperty Path |
  Remove-Item -WhatIf

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:25:17