I need to run the two wmi queries shown below and output the result to a single csv. I have read about and tried to apply it to my own code but not quite there. The below will overwrite the csv every time it cycles around to a new PC and outputs ‘System.object’ under the column IP. At least error detection works!
Anyone have any ideas?
Thanks
$computers = (Get-Content "C:\Powershell\Comps.txt")
ForEach ($computer in $Computers) {
# Test connection to make sure computer is turned on / exists on domain.
IF (Test-Connection -ComputerName $Computer -count 1 -quiet) {
# Query WMI on each machine to return Comp details and IP
$Comps=gwmi win32_computersystem -comp $computer | select USername,dnshostname,Manufacturer,model
$IPs= Gwmi win32_networkadapterconfiguration -Namespace root/cimv2 -comp $Computer |
where {$_.IPAddress} |select -expand ipaddress | where {$_ -like "192.128*"}
foreach ($comp in $comps) {
$IP = $IPs | Where { $_.dnshostname -eq $comps.caption }
$CompInfo = New-Object PSObject -Property @{
ComputerName = $Computer
Username = $Comps.Username
Manufacturer = $Comps.Manufacturer
Model = $Comps.model
IP = $IPs.ipaddress
}
}
# Export to CSV
$CompInfo | export-csv C:\Powershell\Compstest.csv
# If the target system is unresponsive, return following to screen
} ELSE {
$obj = New-Object PSObject -Property @{
Computername = $Computer
IPAddress = 'Unreachable'
}
$obj
}
}
If you have powershell version 3, then Export-CSV has an -Append parameter.
If you are stuck on powershell version 2, then you can redesign your loop to just output objects, no export csv, and assign the output of the loop to a variable. That variable, which holds all the exported objects, can then be exported
I wasn’t totally able to get rid of the System.Object message. We have three Comp OUs, and across 2 of them I get a 99% success rate with few of theses messages. For the last OU half of the returned lines have this message under the IP column.
I just tried running your code for my own machine and it works fine although there is no returned logonserver. Are you seeing the System.Object message where you’d expect to see an IP address?
Also, have you thought about exporting to CSV rather than a text file? Would be easier to read if you are querying multiple machines.