如何使用Powershell中的Select-String cmdlet获取文件的路径

qv7cva1a  于 2023-02-04  发布在  Shell
关注(0)|答案(1)|浏览(250)

我尝试在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命令的行为?

ev7lccsx

ev7lccsx1#

(git status | Select-String -Pattern 'regex-file-name-pattern' -Raw ).Trim() | Remove-Item

此问题与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()方法来删除空白。

相关问题