Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the current powershell pipe-object "$_" as a command line arg?

Tags:

powershell

svn

I'm trying to set all svn:property's on a set of piped files:

dir * -include *.cs | Select-String -simplematch -pattern "HeadURL$" | select filename | svn propset svn:keywords "HeadURL Id LastChangedBy LastChangedRevision" $_

I get following error:

svn: Try 'svn help' for more info
svn: Explicit target required ('HeadURL Id LastChangedBy LastChangedRevision' interpreted as prop value)

The problem is, that $_ is not passed onto svn propset...

What to do?

like image 485
Lars Corneliussen Avatar asked Dec 29 '22 19:12

Lars Corneliussen


1 Answers

For $_ to have a value you have to use it in a context where it is actually set. For your specific scenario this means that you have to wrap your call to svn into a ForEach-Object cmdlet:

dir * -include *.cs | Select-String -simplematch -pattern "HeadURL$" | select filename | % { svn propset svn:keywords "HeadURL Id LastChangedBy LastChangedRevision" $_ }

(I have used the % alias here for brevity)

Inside that ForEach the variable $_ has a value and can be used.

However, I have seen some uses where the current pipeline object got appended to a program's arguments when piping into non-cmdlets. I haven't fully understood that so far, though.

But to understand what you are doing here: You are trying to set svn:keywords on every file which uses one of those. A probably more robust and readable approach would be to actually filter the list you are scanning:

gci * -inc *.cs |
Where-Object {
    (Get-Content $_) -match 'HeadURL$'
}

(might work, haven't tested)

You can then continue by just piping that into a foreach:

| ForEach-Object {
    svn ps svn:keywords "HeadURL Id LastChangedBy LastChangedRevision" $_.FullName
}

Also, here you can access all properties of the file object and not need to rely on the object Select-String gives you.

like image 175
Joey Avatar answered Jan 13 '23 14:01

Joey