I want to build a "~table" that holds information about various computer (e.g. Name, IP Address and MAC Address though more information could be added later). Here is what I have so far:
$Computers = "Server1", "Server2", "Server" #Eventually will get from file
$a = $Computers.length
$User = Read-Host "Enter Username"
$Cred = Get-Credential $User
cls
$ComputerInfo = @{NAME = 1..$a; IP_ADDR = 1..$a; MAC_ADDR = 1..$a}
$i = 0
ForEach ($Computer in $Computers) {
$wmiquery = get-wmiobject win32_networkadapterconfiguration -computer $Computer -filter "IPEnabled='True'" -Credential $Cred
$ComputerInfo.NAME[$i] = $Computer
$ComputerInfo.IP_ADDR[$i] = $wmiquery.IPAddress[0]
$ComputerInfo.MAC_ADDR[$i] = $wmiquery.MACAddress
$i++
}
The code above provides me with the information I want. However, I'm having trouble exporting to csv file / displaying in table. If I simply type: $ComputerInfo
. I get:
Name Value
MAC_ADDR {MAC1, MAC2, MAC3}
IP_ADDR {IP1, IP2, IP3}
NAME {Server1, Server2, Server3}
Not exactly what I'm looking for. I want something more like:
NAME IP_ADDR MAC_ADDR
[value] [value] [value]
[value] [value] [value]
[value] [value] [value]
If I export $ComputerInfo
to CSV file it gets even goofier. I get
TYPE System.Collections.Hashtable
"IsReadOnly","IsFixedSize","IsSynchronized","Keys","Values","SyncRoot","Count"
"False","False","False","System.Collections.Hashtable+KeyCollection","System.Collections.Hashtable+ValueCollection","System.Object","3"
Best Answer
Overall I would make the following adjustments below. A few things I changed around:
Get-Credential
can provide a messagepsobject
, it makes it much easier to work with and referencing columns to set values.psobject
it removes the need to index into the array (e.g. usingcolumn[0]
)When you want to add more columns to your table just expand the
$props
variable with your columns, and populate it in yourforeach
loop.Output of this script just with my local computer:
Then to just show what it will output if I just
ConvertTo-Csv
:EDIT
One thing to just add that you will see a difference with your
$computerinfo
versus mine above is the TypeName. If you pipe it toGet-Member
your object will return asSystem.Collections.Hashtable
, where mine is going to return as aSystem.Management.Automation.PSCustomObject
. ThePSCustomObject
will return each column in your table as aNoteProperty
type that you can use in your script as you build onto it (e.g. querying the domain for Computer information).