I can't figure out why the following code fails:
# test.ps1
"`$args: ($args)"
"`$args count: $($args.length)"
# this fails
0..$($args.length - 1) | %{ $args[$_] = ($args[$_] -replace '`n',"`n") }
# this works
$i = 0
foreach ( $el in $args ) { $args[$i] = $args[$i] -replace '`n',"`n"; $i++ }
"$args"
I'm calling it like so:
rem from cmd.exe
powershell.exe -noprofile -file test.ps1 "a`nb" "c"
Scoping issue. The $args inside the foreach-object (%) scriptblock is local to that scriptblock. The following works:
"`$args: $args"
"`$args count: $($args.length)"
$a = $args
# this fails
0..$($args.length - 1) | %{ $a[$_] = ($a[$_] -replace '`n',"`n") }
$a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With