【问题标题】:How to iterate through an array of objects in Powershell如何遍历Powershell中的对象数组
【发布时间】:2021-03-08 21:22:04
【问题描述】:

我正在对表单字段进行一些基本验证。遍历对象数组以验证它们的正确方法是什么?当我尝试以下方法时,我得到了

在此对象上找不到属性“BackColor”。验证该属性是否存在并且可以设置。

我想我缺少的是告诉 Powershell 这些是对其他变量的引用,而不是变量本身的方法。

$MandatoryFields = @(
    'txtUsername',
    'txtFirst',
    'txtLast',
    'txtEmail',
    'ComboLicense'
)

ForEach ($Field in $MandatoryFields) {
    If ([string]::IsNullOrWhitespace($Field.text)) {
        $Validation = "failed"
        $Field.BackColor = "red"
    }
}

编辑:好的,我需要的是数组中的实际变量,如下所示:

$MandatoryFields = @(
    $txtUsername,
    $txtFirst,
    $txtLast,
    $txtEmail,
    $ComboLicense
)

【问题讨论】:

  • 不确定,我明白,但是,这有帮助吗stackoverflow.com/questions/37688708/…
  • 不这么认为。所以在我的示例中,我在脚本中有对象 - txtUsername、txtFirst 等 - 我已经在 $MandatoryFields 数组中写下了这些对象的名称。我想对 ForEach 循环中的每个对象执行此操作。我想用实际对象来做这些事情,而不是用我在 $MandatoryFields 数组中编写的那些对象的名称。这有意义吗?
  • 换句话说,我需要告诉 Powershell - 不要担心这个数组中的文本 'txtUsername' - 而是去查看这个脚本中其他地方的实际 txtUsername 对象并给我一个属性...
  • 你想用这些对象做什么,你能给出更多的上下文吗?
  • 基本上我想读取一堆对象的 Text 属性,检查它是否为空,如果是,则将该对象的 BackColor 属性更改为红色。我想用一组对象名称来做,而不是用几十个 IF 语句。

标签: powershell


【解决方案1】:

我假设您使用 System.Windows.Forms 创建表单。如果在添加控件时出现这种情况,您应该为控件指定一个名称。然后您可以遍历您的控件并检查控件名称是否与您的强制控件列表匹配,然后执行您的检查。

$MandatoryFields = @(
    'txtUsername',
    'txtFirst',
    'txtLast',
    'txtEmail',
    'ComboLicense'
)

$Controls = MyForm.controls

ForEach ($c in $Controls) {
    ForEach ($Field in $MandatoryFields) {
        if ($c.Name -eq $Field) {
            If ([string]::IsNullOrWhitespace($c.text)) {
                $Validation = "failed"
                $c.BackColor = "red"
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    尝试将您的对象添加到如下数组中

    $objects = [System.Collections.ArrayList]@()
    
    $myObject = [PSCustomObject]@{
        Name     = 'Kevin'
        Language = 'PowerShell'
        State    = 'Texas'
    }
    
    
    $objects.add($myObject)
    
    $myObject1= [PSCustomObject]@{
        Name     = 'Kevin'
        Language = 'PowerShell'
        State    = 'Texas'
    }
    
    
      $objects.add($myObject1)
    
    foreach($obj in $objects){
    
    $obj.firstname
    
    }
    

    【讨论】:

    • 数组不可扩展,所以在这种情况下使用 ArrayList 或 List[object] 之类的东西可能更好,不是吗?否则,您每次调用 += 时都会处理一个全新的数组
    猜你喜欢
    • 1970-01-01
    • 2022-11-17
    • 2020-12-03
    • 2021-02-25
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    相关资源
    最近更新 更多