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

使用Get-ChildItem时,能否自动推断Remove-Item的目标路径?

PowerShell中Remove-Item自动推断路径的实现

当然可以用Remove-Item $_替代重复指定路径的写法,甚至还有更简洁的方式。

当你用Get-ChildItem获取文件/目录对象并通过管道传递时,$_作为PowerShell的自动变量,代表管道中的当前对象。Remove-Item能够直接识别这个对象包含的路径信息,不需要手动拼接或重复输入路径。

举个实际例子:

原写法(重复路径)

Get-ChildItem -Path "D:\Test\*.tmp" | ForEach-Object { Remove-Item -Path "D:\Test\$($_.Name)" }

优化写法(使用$_)

Get-ChildItem -Path "D:\Test\*.tmp" | ForEach-Object { Remove-Item $_ }

更简洁的写法(省略ForEach-Object)

其实连ForEach-Object都可以省掉,直接把Get-ChildItem的结果管道传给Remove-Item,它会自动处理每个对象:

Get-ChildItem -Path "D:\Test\*.tmp" | Remove-Item

如果要删除只读文件或者跳过确认操作,可以加上对应参数,比如-Force强制删除,-Confirm:$false取消确认提示:

Get-ChildItem -Path "D:\Test\*.tmp" | Remove-Item -Force

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:22:38