ali*_*ikk 0 arrays powershell reference
我想收集有关域中主机的一些信息,因此我尝试编写如下内容:
# declare array for storing final data
$servers_list = @()
#start with a list of servers and go through collecting the info
$servers | ForEach-Object {
$sys = Get-WmiObject Win32_computersystem -ComputerName $_
# create new custom object to store information
$server_obj = New-Object –TypeName PSObject
$server_obj | Add-Member –MemberType NoteProperty –Name Domain –Value $sys.Domain
# .... add all other relevant info in the same manner
# Add server object to the array
$servers_list += $server_obj
}
Run Code Online (Sandbox Code Playgroud)
这段代码的问题是我将对象的引用传递给数组而不是实际的对象。所以当我的循环完成时,我最终得到一个数组,其中包含看起来都一样的行:(
知道如何将实际对象传递到数组中,而不仅仅是对它的引用吗?另一个想法是动态声明新对象而不是每次都使用$server_obj变量,但我也不知道如何做到这一点......
谢谢!!!
您可以构建一个对象数组并像这样不断向它们动态添加信息:
#This will be your array of objects
#In which we will keep adding objects from each computer
$Result = @()
#start with a list of servers and go through collecting the info
$servers | ForEach-Object {
$sys = Get-WmiObject Win32_computersystem -ComputerName $_
# create new custom object to keep adding store information to it
$Result += New-Object –TypeName PSObject -Property @{Domain = $sys.Domain;
Name = $sys.Name;
SystemType = $sys.SystemType
}
}
# Get back the objects
$Result
Run Code Online (Sandbox Code Playgroud)
其中 Domain、Name 和 SystemType 是您要与对象关联的属性。
| 归档时间: |
|
| 查看次数: |
6663 次 |
| 最近记录: |