Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error trying to loop through $args in script file using range notation for loop index

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"
like image 380
guillermooo Avatar asked Jan 22 '23 11:01

guillermooo


1 Answers

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
like image 124
Keith Hill Avatar answered Apr 26 '23 12:04

Keith Hill