尝试使用循环索引的范围表示法循环遍历脚本文件中的 $args 时出错
我不明白为什么下面的代码失败:
# 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"
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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
范围界定问题。 foreach-object (%) 脚本块内的 $args 是该脚本块的本地变量。以下作品:
Scoping issue. The $args inside the foreach-object (%) scriptblock is local to that scriptblock. The following works:
基思回答了这个问题。只是想添加更多信息,因为我发现它很多次很有用。看一下代码:
-replace
运算符也适用于数组!Keith answered this question. Just wanted to add some more info, because I found it useful many times. Look at the code:
The
-replace
operator works with array too!