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

I cannot understand 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 call it this:

 rem from cmd.exe powershell.exe -noprofile -file test.ps1 "a`nb" "c" 
+4
source share
2 answers

Definition problem. $ Args inside the script script foreach-object (%) is local to this script block. The following works:

 "`$args: $args" "`$args count: $($args.length)" $a = $args # this fails 0..$($args.length - 1) | %{ $a[$_] = ($a[$_] -replace '`n',"`n") } $a 
+7
source
Kate answered this question. I just wanted to add more information because I found it useful many times. Take a look at the code:
 [21]: function test{ >> $args -replace '`n',"`n" >> } >> [22]: test 'replace all`nnew' 'lines`nin the `nstring' 'eof`ntest' replace all new lines in the string eof test 

The -replace operator also works with an array!

+2
source

Source: https://habr.com/ru/post/1302928/


All Articles