1

I'm using the following Powershell command to copy one user's Mercurial.ini file into another user's profile:

> copy $env:USERPROFILE\..\benm\Mercurial.ini $env:USERPROFILE\..\alex\Mercurial.ini

That works well. However, I'd like to write it in such as way so that I can do something like the following, specifying the users up front and piping them in to the copy command:

> "benm","alex" | copy "$env:UserProfile\..\$_[0]\Mercurial.ini" "$env:UserProfile\..\$_[1]\Mercurial.ini"

However, the above doesn't work. Is there an elegant way to achieve what I'm trying to do?

1 Answer 1

3

Something like this?

,("benm","alex") | 
foreach {copy "$env:UserProfile\..\$($_[0])\Mercurial.ini" "$env:UserProfile\..\$($_[1])\Mercurial.ini"}

The ,("benm","alex") syntax makes the input from the pipeline a 2D array

 PS C:\> $x = ,("benm","alex")
 PS C:\> $x[0]
 benm
 alex
 PS C:\> $x[0][0]
 benm
 PS C:\> $x[0][1]
 alex

The Powershell pipeline will automatically "unroll" arrays and collections into a stream of objects, but only one level deep for nested arrays. By making it a 2D array, it "unrolls" the first level, and passes the nested array through the pipelile intact.

Sign up to request clarification or add additional context in comments.

5 Comments

Good catch.That's a consequence of using an array element in a string argument. You must use a sub-expression to get the array element to expand.
You might want to explain what ,( ) is doing. It's a neat trick.
Updated the answer with some explanation of the ,( ) syntax.
is there a way to get powershell to not unroll the array? I like your trick, but it seems a bit much
Not that I know of. It's pretty well hard-wired into it. That's how you get an array into the pipeline. You can give it the user names in an argumentlist, but that's not using the pipeline and you'd have to use $args instead of $_.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.