4

我无法弄清楚为什么以下代码失败:

# 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"
4

2 回答 2

7

范围问题。foreach-object (%) 脚本块中的 $args 是该脚本块的本地变量。以下作品:

"`$args: $args" 
"`$args count: $($args.length)" 
$a = $args

# this fails 
0..$($args.length - 1) | %{ $a[$_] = ($a[$_] -replace '`n',"`n") } 
$a
于 2010-03-03T00:31:50.710 回答
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数组!

于 2010-03-03T05:41:30.710 回答