Powershell: Hashtable & PSCustomObject 区别
哈希表 是一种数据结构,用于存储键值对(也称为字典或者关联数组)
语法:
$Var = @{ <key1> = <value1> ; < key2> = <value2> ; ..... ; < keyN> = <valueN>;}
example:
创建哈希表
$employee = @{name = "Allen";age =40 ; address ="abc"}
PSCustomObject
旨在于用简单的方法来创建结构化数据
$myObject = [PSCustomObject]@{
Name = 'Allen'
age = '40l'
address = 'abc'
}
or
$myHashtable = @{
Name = 'Allen'
age = '40'
address = 'abc'
}
$myObject = [pscustomobject]$myHashtable
区别:
使用 [PSCustomObject]
而不是HashTable的一种情况是
在需要它们的集合时.以下是说明它们处理方式的不同之处:
$Hash = 1..10 | %{ @{Name="Object $_" ; Index=$_ ; Squared = $_*$_} } $Custom = 1..10 | %{[PSCustomObject] @{Name="Object $_" ; Index=$_ ; Squared = $_*$_} } $Hash | Format-Table -AutoSize $Custom | Format-Table -AutoSize $Hash | Export-Csv .\Hash.csv -NoTypeInformation $Custom | Export-Csv .\CustomObject.csv -NoTypeInformation
Format-Table
将产生以下结果$Hash
:
Name Value ---- ----- Name Object 1 Squared 1 Index 1 Name Object 2 Squared 4 Index 2 Name Object 3 Squared 9
...
以下是$CustomObject
:
Name Index Squared ---- ----- ------- Object 1 1 1 Object 2 2 4 Object 3 3 9 Object 4 4 16 Object 5 5 25 ...
以上不同的举例来自于
https://qa.1r1g.com/sf/ask/980894141/
本文来自博客园,作者:Abstracthinking,转载请注明原文链接:https://www.cnblogs.com/Abstracthinking/p/16689389.html