Home > Blockchain >  How to get the path of the file using the Select-String cmdlet in Powershell
How to get the path of the file using the Select-String cmdlet in Powershell

Time:01-21

I'm trying to replicate the following behavior in 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 '{}'

In Powershell, I tried:

git status | Select-String 'file-name-pattern' -List | Remove-Item

and got the error:

Remove-Item: Cannot find path 'T:\my-app\.ci\InputStream' because it does not exist.

I have tried many variants of the above powershell command, but did not work. How can I replicate the behavior of the above linux command in powershell ?

CodePudding user response:

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

The issue is related to the object output of the Select-String command. By default Select-String creates Microsoft.PowerShell.Commands.MatchInfo objects with a Path property containing the path of the input which in this case would be 'InputStream'. Remove-Item binds to this Path property and assumes it is a filename. Since a full path is not provided it assumes the current path and tries to delete a file with this name and reports that it Cannot find path 'T:\my-app\.ci\InputStream'

To get the desired behavior of sending any matched filename lines directly as strings to Remove-Item we can include the -Raw switch to Select-String which will result in the matched lines being bound to the -Path parameter of Remove-Item. Unfortunately due to the whitespace caused by the indention of the filename by git status Remove-Item will still fail to find the file. To correct for this, we call the Trim() method on the outputted strings to remove the whitespace.

  • Related