【问题标题】:Why is PowerShell creating a Char Array instead of a String Array?为什么 PowerShell 创建字符数组而不是字符串数组?
【发布时间】:2020-02-12 22:03:16
【问题描述】:

当我在数组的数组中输出元素时(例如:$data_array[0][0],我只得到一个字符。这是为什么呢?我期待 [0][ 的字符串为 LAP-150 0] 这个数组的位置。

import-module activedirectory
$domain_laptops = get-adcomputer -filter 'Name -like "LAP-150"' -properties operatingsystem, description | select name, description, operatingsystem
$data_array = @()

foreach ($laptop in $domain_laptops){
        $bde = manage-bde -computername $laptop.name -status
        $encryptionstatus=(manage-bde -status -computername $laptop.name | where {$_ -match 'Conversion Status'})
        if ($encryptionstatus){
            $encryptionStatus=$encryptionstatus.split(":")[1].trim()
        }
        else{
            $EncryptionStatus="Not Found..."
        }
        $data_array += ,($laptop.name,$laptop.description,$laptop.operatingsystem,$encryptionstatus)
    }


write-output $data_array[0][0]

上述脚本的输出只是字符“L”,它是 $laptop.name 变量中的第一个字符。我哪里错了?我认为这与我附加到数组的方式有关,但我尝试了不同的括号、逗号、无括号等组合,但无济于事。

【问题讨论】:

    标签: arrays powershell loops


    【解决方案1】:

    当你运行以下命令时,

    $data_array += ($laptop.name,$laptop.description,$laptop.operatingsystem,$encryptionstatus)
    

    删除+= 符号后的,

    进行的测试向您展示其工作原理

    $array = @()
    $array = 1, 2, 3, 4
    $array.Length   //-> 4
    
    $array2 = @()
    $array2 = , 1, 2
    $array2.Length  //-> 2
    
    $array3 = @()
    $array3 = , (1, 2)
    $array3.Length  //-> 1
    
    $array4 = @()
    $array4= @(), (1, 2)
    $array4.Length  //-> 2
    

    使用,时,必须前后定义相同类型的元素。在您的迭代过程中,您使用的是+= , (something)。的左边,没有任何数据,所以后面的所有文本都被认为是一个用逗号分隔的字符串。

    对于二维数组,我建议在混合中使用散列,

    $data_array += @{name=$laptop.name;description=$laptop.description;os=$laptop.operatingsystem;encryption=$encryptionstatus}
    
    $data_array[0]["name"] // Prints the name of first laptop in array.
    

    【讨论】:

    • 我不认为这是正确的。当我检查 $data_array[0] 的输出时,我得到的不仅仅是 $laptop.name。我在 ONE 行中获得了 $laptop.name、$laptop.description、$laptop.operatingsystem 和 $encryption 状态。我相信这些都被视为数组中的一个元素,但不知何故被视为字符串而不是数组。
    • Right.. 需要在您插入的数组之前删除第一个 ,。删除+= 之后和($laptop.name) 之前的,
    • 这有帮助!唯一的问题是我仍然需要在数组中包含数组。我将使用更多的 LAP-### 来运行它,而不仅仅是一个。如何让 $laptop.name、$laptop.description、$laptop.operatingsystem 和 $encryptionstatus 成为它们自己的数组,然后为每台笔记本电脑添加一个新数组到二维数组中的数组?
    • 对不起,如果我的描述不够清楚,但这是我的预期目标
    • 同意这是个人喜好。如果我没有明确表示我是在发表意见,我深表歉意。我使用 PSCustomObjects 是因为它具有互操作性以及它们在其他地方管道时的表现如何。
    猜你喜欢
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2012-07-03
    • 1970-01-01
    相关资源
    最近更新 更多