我无法弄清楚以下代码失败的原因:
# 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"
我这样称呼它:
rem from cmd.exe
powershell.exe -noprofile -file test.ps1 "a`nb" "c"
答案 0 :(得分:7)
范围问题。 foreach-object(%)scriptblock中的$ args是该scriptblock的本地。以下作品:
"`$args: $args"
"`$args count: $($args.length)"
$a = $args
# this fails
0..$($args.length - 1) | %{ $a[$_] = ($a[$_] -replace '`n',"`n") }
$a
答案 1 :(得分:2)
[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
-replace
运算符也适用于数组!