为什么PowerShell要创建字符数组而不是字符串数组?



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

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 变量中的第一个字符。我哪里出错了?我认为这与我如何附加到数组有关,但我尝试了括号、逗号、无括号等的不同组合,但无济于事。

当您运行以下命令时,

$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).的左侧没有任何数据,因此它之后的所有文本都被视为用逗号分隔的字符串。

对于 2D 数组,我建议在混合中使用哈希,

$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.