提问人:ajra 提问时间:8/17/2023 最后编辑:mklement0ajra 更新时间:8/18/2023 访问量:40
Power shell:当我使用 forEach 时,无法影响变量的值
Power shell: can't affect a value to variable When I use forEach
问:
$variable = "test", "test1", "test2", "","test3"
Write-Host $variable
foreach($item in $variable)
{
if (-not $item -or $item -eq "") {
$item ="N/A"
}
}
Write-Host $variable
- 这是 OuptPut: test test1 test2 test3
- 这是我所期望的: test test1 test2 N/A test3
答:
3赞
Mathias R. Jessen
8/17/2023
#1
.NET 中的字符串是不可变的,并按值传递 - 当您为其分配新值时,不会影响从数组中提取的现有字符串值。$item
$variable
使用循环写回数组:for
for($i = 0; $i -lt $variable.Count; $i++) {
if ([string]::IsNullOrEmpty($variable[$i])) {
$variable[$i] = "N/A"
}
}
1赞
mklement0
8/17/2023
#2
为了补充 Mathias 有用的答案,它显示了对数组的就地修改,并利用了创建新数组的替代方案,利用了您可以在 PowerShell 中使用整个语句作为表达式的事实,并将结果自动收集到数组中(如果有两个或多个输出对象)。
$variable = "test", "test1", "test2", "","test3"
# Note:
# If you want to ensure that $variable remains an array even if the loop
# outputs just *one* string, use:
# [array] $variable = ...
$variable =
foreach ($item in $variable) { if (-not $item) { 'N/A' } else { $item } }
注意:
-not $item
根据 PowerShell 的自动到布尔转换规则,足以检测空字符串和值,这些规则在此答案的底部进行了总结。$null
虽然就地更新的内存效率更高,但对于较小的阵列,创建新的阵列并不是一个问题。
评论