我无法从作为数组一部分的对象中列出每个元素的键和值。
从代码中可以看到,我已经将对象添加到数组中,但是我只是无法获得所需的$ finalList。
$date = Get-Date
$userInfo = Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True'"
$userAccount = New-Object System.Collections.ArrayList
foreach ($user in $userInfo) {
$userAccount += (@{
"Name"=$user.Name;
"Status"=$user.Status;
"Disabled"=$user.Disabled;
"AccountType"=$user.AccountType;
"Lockout"=$user.Lockout;
"PasswordRequired"=$user.PasswordRequired;
"PasswordChangeable"=$user.PasswordChangeable;
"SID"=$user.SID;
})
}
foreach ($item in $userAccount) {
$temp = New-Object System.Object
$temp | Add-Member -MemberType NoteProperty -Name "Date" -Value "$date"
$temp | Add-Member -MemberType NoteProperty -Name "Hostname" -Value "$env:computername"
$temp | Add-Member -MemberType NoteProperty -Name "Key" -Value "$($item.Keys)"
$temp | Add-Member -MemberType NoteProperty -Name "Value" -Value "$($item.Values)"
$finalList.Add($temp) | Out-Null
}
使用$ finalList,我希望有一列日期,主机名和另外两列,其中包含$ userAccount数组中的键和值。 $ finalList将导出到csv。
答案 0 :(得分:1)
这对我有用。从您没有声明第二个arraylist的事实来看,您的代码似乎可以正常工作。
$date = Get-Date
$userInfo = Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True'"
$userAccount = New-Object System.Collections.ArrayList
foreach ($user in $userInfo) {
$userAccount += (@{
"Name"=$user.Name;
"Status"=$user.Status;
"Disabled"=$user.Disabled;
"AccountType"=$user.AccountType;
"Lockout"=$user.Lockout;
"PasswordRequired"=$user.PasswordRequired;
"PasswordChangeable"=$user.PasswordChangeable;
"SID"=$user.SID;
})
}
$finalList = New-Object System.Collections.ArrayList
foreach ($item in $userAccount) {
$temp = New-Object System.Object
$temp | Add-Member -MemberType NoteProperty -Name "Date" -Value "$date"
$temp | Add-Member -MemberType NoteProperty -Name "Hostname" -Value "$env:computername"
$temp | Add-Member -MemberType NoteProperty -Name "Key" -Value "$($item.Keys)"
$temp | Add-Member -MemberType NoteProperty -Name "Value" -Value "$($item.Values)"
$finalList.Add($temp) | Out-Null
}
$finalList | Export-Csv 'C:\path\to\file.csv' -NoTypeInformation
答案 1 :(得分:0)
PowerShell会自动将$ finalList设置为数组列表,但最好声明它,因为由于某些原因,即使$ finalList.GetType()会产生相同的结果,它也不会有相同的表现。枚举哈希表$ item将使我能够根据需要获取键/值对。
$finalList = New-Object System.Collections.ArrayList
foreach ($item in $userAccount) {
$item.GetEnumerator() | ForEach-Object {
$temp = New-Object System.Object
$temp | Add-Member -MemberType NoteProperty -Name "Date" -Value "$date"
$temp | Add-Member -MemberType NoteProperty -Name "Hostname" -Value "$env:computername"
$temp | Add-Member -MemberType NoteProperty -Name "Key" -Value $_.Key
$temp | Add-Member -MemberType NoteProperty -Name "Value" -Value $_.Value
$finalList.Add($temp) | Out-Null
}
}
$finalList