我尝试在Powershell (version 7.2.8)
中复制以下行为:
# use `grep` to select file names from output of `git status` and delete them
git status | grep 'file-name-pattern' | xargs -I '{}' rm '{}'
在Powershell中,我尝试:
git status | Select-String 'file-name-pattern' -List | Remove-Item
并得到错误:
Remove-Item: Cannot find path 'T:\my-app\.ci\InputStream' because it does not exist.
我已经尝试了上面的powershell命令的许多变体,但都不起作用。我怎样才能在powershell中复制上面的linux命令的行为?
1条答案
按热度按时间ev7lccsx1#
此问题与
Select-String
命令的对象输出有关。默认情况下,Select-String
创建具有Path属性的Microsoft.PowerShell.Commands.MatchInfo
对象,该属性包含输入的路径,在本例中为“InputStream”。Remove-Item
绑定到此Path属性并假定它是文件名。由于未提供完整路径,因此它将采用当前路径并尝试删除具有此名称的文件,并报告该文件为Cannot find path 'T:\my-app\.ci\InputStream'
要获得将任何匹配的文件名行作为字符串直接发送到
Remove-Item
的预期行为,我们可以将-Raw
开关包含到Select-String
,这将导致匹配的行绑定到Remove-Item
的-Path
参数。不幸的是,由于文件名缩进git status
导致的空白,Remove-Item
仍然无法找到该文件。我们对输出的字符串调用Trim()
方法来删除空白。