$variable = "test", "test1", "test2", "","test3"
Write-Host $variable
foreach($item in $variable)
{
if (-not $item -or $item -eq "") {
$item ="N/A"
}
}
Write-Host $variable
- 这是输出:test test1 test2 test3
- 这就是我所期望的:测试 test1 test2 N/A test3
最佳答案
.NET 中的字符串是不可变的并按值传递 - 当您为 $item
分配新值时,它不会影响从 $variable
中提取的现有字符串值> 数组。
使用for
循环写回数组:
for($i = 0; $i -lt $variable.Count; $i++) {
if ([string]::IsNullOrEmpty($variable[$i])) {
$variable[$i] = "N/A"
}
}
关于arrays - Powershell : can't affect a value to variable When I use forEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76921768/