powershell:遍历所有数组,如果空,请按默认值
有多个数组,它们的内容可能会或可能不会为空。如果这些数组中的任何一个是空的,我想向它们添加默认值。
我尝试将所有数组包装到容器阵列中,并使用foreach-object
,但是似乎未分配默认值。
#...
$arr1 = @()
$arr2 = @("a","b")
$arr3 = @("c","d")
@($arr1, $arr2, $arr3 | ForEach-Object {
if($_.Count -le 0) {
$_ = @("EMPTY")
}
})
Write-Output $arr1
# ...
未分配空数组
PS> $arr1
PS> <# NOTHING #>
是否可以为这些数组设置默认值?
There are multiple arrays, and their contents might or might not be empty. If any of these arrays are empty, I would like to add a default value to them.
I have tried wrapping all the arrays into a container array and using Foreach-Object
, but the default value does not appear to be assigned.
#...
$arr1 = @()
$arr2 = @("a","b")
$arr3 = @("c","d")
@($arr1, $arr2, $arr3 | ForEach-Object {
if($_.Count -le 0) {
$_ = @("EMPTY")
}
})
Write-Output $arr1
# ...
The empty array was not assigned
PS> $arr1
PS> <# NOTHING #>
Is it possible to set a default value for those arrays?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在尝试修改变量,而不是其 value 。
因此,您必须枚举变量对象,您可以使用
get-variable
:另外,请考虑将数组保留在单个空语中,而不是在单个变量中保持:
You're trying to modify variables, not their values.
Therefore, you must enumerate variable objects, which you can obtain with
Get-Variable
:Alternatively, consider maintaining your arrays in a single hashtable rather than in individual variables: