0

I use

for ($i = 0; $i -le 3; $i++) {
Get-ChildItem -path $somepath|Copy-Item -Destination "c:\somefolder\$i-${$_.Name}"
}

But the destination path never translated from variables to right letters. There what I mean: assume $i = 2 and $_.name = file.exe

"c:\somefolder\$i-${$.Name}" going to c:\somefolder\2-"
"c:\somefolder\$i-$($
.Name)" going to c:\somefolder\2-"
"c:\somefolder\${$.Name}$i" going to c:\somefolder\2-"
"c:\somefolder\${$
.Name}" going to c:\somefolder\2-"
but "c:\somefolder\${$_.Name}" going to c:\somefolder\file.exe"

What am I doing wrong? How can I combine two variables together

1 Answer 1

1

You can't access the $_ in a string like that but you can inside a scriptblock if the scriptblock is used as the argument for a parameter that accepts pipeline input e.g.:

for ($i = 0; $i -le 3; $i++) {
    Get-ChildItem $somepath | Copy-Item -Destination {"c:\somefolder\$i-$($_.Name)"} 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it worked. But can you explain why that behaviour occur?
The $_ is typically only available within a scriptblock inside the pipeline like | Foreach {<$_ injected here>} or | Where {<$_ injected here>}. If a parameter is configured for pipeline binding (you can see this in the help on Copy-Item Destination parameter) then PowerShell allows you to use a scriptblock to determine the value for that parameter. The bonus is that PowerShell will inject $_ into that scriptblock so you can reference it there. See item 8 & 9 in this free ebook skydrive.live.com/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.