Question

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

Était-ce utile?

La solution

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)"} 
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top