powershell:遍历所有数组,如果空,请按默认值

发布于 2025-02-12 05:07:43 字数 510 浏览 2 评论 0原文

有多个数组,它们的内容可能会或可能不会为空。如果这些数组中的任何一个是空的,我想向它们添加默认值。

我尝试将所有数组包装到容器阵列中,并使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素罗衫 2025-02-19 05:07:43

您正在尝试修改变量,而不是其 value
因此,您必须枚举变量对象,您可以使用 get-variable

$arr1 = @()
$arr2 = @("a","b")
$arr3 = @("c","d")

Get-Variable arr* | ForEach-Object {
  if ($_.Value.Count -eq 0) {
    $_.Value = @("EMPTY")
  }
}

$arr1 # -> @('EMPTY')

另外,请考虑将数组保留在单个空语中,而不是在单个变量中保持:

$arrays = [ordered] @{
  arr1 = @()
  arr2 = @("a","b")
  arr3 = @("c","d")
}

foreach ($key in @($arrays.Keys)) {
  if ($arrays.$key.Count -eq 0) {
    $arrays.$key = @('EMPTY')
  }
}

$arrays.arr1 # -> @('EMPTY')

You're trying to modify variables, not their values.
Therefore, you must enumerate variable objects, which you can obtain with Get-Variable:

$arr1 = @()
$arr2 = @("a","b")
$arr3 = @("c","d")

Get-Variable arr* | ForEach-Object {
  if ($_.Value.Count -eq 0) {
    $_.Value = @("EMPTY")
  }
}

$arr1 # -> @('EMPTY')

Alternatively, consider maintaining your arrays in a single hashtable rather than in individual variables:

$arrays = [ordered] @{
  arr1 = @()
  arr2 = @("a","b")
  arr3 = @("c","d")
}

foreach ($key in @($arrays.Keys)) {
  if ($arrays.$key.Count -eq 0) {
    $arrays.$key = @('EMPTY')
  }
}

$arrays.arr1 # -> @('EMPTY')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文