r/PowerShell • u/CRTejaswi • May 10 '26
Question Unexpected Behaviour with `args[$_]`
This snippet:
function lf {
if ($args){
(0..($args.Count-1) | %{ "$args[$_]" }) -join ','
(0..($args.Count-1) | %{ "$($args[$_])" }) -join ','
} else{
...
}
}
lf pdf png txtprints:
[0],[1],[2]
,,instead of the expected pdf,png,txt. Why?
I'm concerned with 0..N | args[$_] failing (but args[N] works) even though the syntax pipes well to most objects/cmdlets.
⚠️ RESOLVED, thanks to surfingoldelephant.
8
Upvotes
View all comments
Show parent comment
2
u/iBloodWorks May 10 '26 edited May 10 '26
"$args[Index]" $args was already converted to a String and $_ was Just pulling the respective String Index
Edit: nevermind, it prints the Array and then your respective number of the Loop (currently held by $_) which then gets messed Up by -join
Currently on mobile hard for me to test