I have this piece of code that gets the information from the computers in the domain and outputs to a csv file. I tried to add a new line of code to also grab t he Disk information for the computers but I can't get it working as expected.
# Get the list of all computer names and export to CSV file
Get-ADComputer -Filter * | select Name | Export-Csv -Path 'C:\temp\computers.csv' -NoTypeInformation
# Import the computer names from CSV file and get the system information
$computers = Import-Csv “C:\Temp\computers.csv” | ForEach {
$computerSystem = Get-WmiObject Win32_ComputerSystem -ComputerName $_.Name
$computerOS = Get-WmiObject Win32_OperatingSystem -ComputerName $_.Name
$computerCPU = Get-WmiObject Win32_Processor -ComputerName $_.Name
$computerSN = Get-WmiObject Win32_bios -ComputerName $_.Name | Select-Object SerialNumber
$computerDisk = Get-WmiObject win32_logicaldisk -ComputerName $_.Name | Select-Object DeviceId
[PSCustomObject]#{
'PCName' = $computerSystem.Name
'Model' = $computerSystem.Model
'RAM' = "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB)
'CPU' = $computerCPU.Name
'OS' = $computerOS.caption
'SN' = $computerSN.SerialNumber
'User' = $computerSystem.UserName
'Disk' = $computerDisk.DeviceId | Format-Table DeviceId, MediaType, #{n="Size";e={[math]::Round($_.Size/1GB,2)}},#{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}
}
} | Export-Csv 'C:\Temp\system-info.csv' -NoTypeInformation
This is the line of codes for disk.
$computerDisk = Get-WmiObject win32_logicaldisk -ComputerName $_.Name | Select-Object DeviceId
And...
'Disk' = $computerDisk.DeviceId | Format-Table DeviceId, MediaType, #{n="Size";e={[math]::Round($_.Size/1GB,2)}},#{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}
The other parameters work but only the disk info section isn't working. the output is: System.Object[] instead of displaying the info .
This has worked or me somewhat but it only grabs the info for the first drive. Also, the free space is larger than the Disk size which is weird.
$Computers = Import-Csv 'C:\Temp\computers.csv'
$Computers | ForEach {
$computerSystem = Get-WmiObject Win32_ComputerSystem -ComputerName $_.Name
$computerOS = Get-WmiObject Win32_OperatingSystem -ComputerName $_.Name
$computerCPU = Get-WmiObject Win32_Processor -ComputerName $_.Name
$computerSN = Get-WmiObject Win32_bios -ComputerName $_.Name | Select-Object SerialNumber
$computerDisk = Get-WmiObject win32_logicaldisk -ComputerName $_.Name | Select-Object DeviceId, Size, FreeSpace
[PSCustomObject]#{
'PCName' = $computerSystem.Name
'Model' = $computerSystem.Model
'RAM' = "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB)
'CPU' = $computerCPU.Name
'OS' = $computerOS.caption
'SN' = $computerSN.SerialNumber
'User' = $computerSystem.UserName
'Disk' = $computerDisk.DeviceId | Format-Table | Out-String
'Size' = $computerDisk.Size | Format-Table | Out-String
'Free Space' = $computerDisk.FreeSpace | Format-Table | Out-String
}
} | Export-Csv 'C:\Temp\system-info.csv' -NoTypeInformation
You can do this to get the result I think you're after:
$Computers = Import-Csv 'C:\Temp\computers.csv'
$Computers | ForEach {
$computerSystem = Get-WmiObject Win32_ComputerSystem -ComputerName $_.Name
$computerOS = Get-WmiObject Win32_OperatingSystem -ComputerName $_.Name
$computerCPU = Get-WmiObject Win32_Processor -ComputerName $_.Name
$computerSN = Get-WmiObject Win32_bios -ComputerName $_.Name | Select-Object SerialNumber
$computerDisk = Get-WmiObject win32_logicaldisk -ComputerName $_.Name | Select-Object DeviceId, MediaType, #{n="Size";e={[math]::Round($_.Size/1GB,2)}},#{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}
[PSCustomObject]#{
'PCName' = $computerSystem.Name
'Model' = $computerSystem.Model
'RAM' = "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB)
'CPU' = $computerCPU.Name
'OS' = $computerOS.caption
'SN' = $computerSN.SerialNumber
'User' = $computerSystem.UserName
'Disk' = $computerDisk | Format-Table | Out-String
}
} | Export-Csv 'C:\Temp\system-info.csv' -NoTypeInformation
The first problem was that in the $computerDisk = line you were using Select-Object to return only the DeviceID property, but then were later trying to use the other properties.
The second problem was that you need to pipe Format-Table to Out-String when you output it to convert it to string format so that Export-CSV doesn't treat it as an object.
Related
Get-WmiObject -Class Win32_OperatingSystem -ComputerName (Get-Content "C:\Temp\Servers.txt") | SELECT-Object PSComputerName, #{Name="Memory (RAM in GB)";Expression={[Math]::Round($_.TotalVisibleMemorySize/1024/1024)}} | Format-Table
Get-WmiObject -Class Win32_logicaldisk -ComputerName (Get-Content "C:\Temp\Servers.txt") | Select-Object PSComputerName, DriveType, DeviceID, VolumeName, #{Name="Size";Expression={[math]::ceiling($_.Size /1GB)}} , #{Name="FreeSpace";Expression={[math]::ceiling($_.FreeSpace /1GB)}}, Compressed | where DriveType -eq 3 | Format-Table
Get-WmiObject -Class Win32_OperatingSystem -ComputerName (Get-Content "C:\Temp\Servers.txt")| Select-Object PSComputerName, BuildNumber, BuildType, Caption, CodeSet, OSArchitecture, SystemDrive, TotalVisibleMemorySize, Version | Format-Table
Get-WmiObject -Class win32_product -ComputerName (Get-Content "C:\Temp\Servers.txt") | Select-Object Name, Version, Vendor, InstallDate | Format-Table
Get-WmiObject -Class Win32_Service -ComputerName (Get-Content "C:\Temp\Servers.txt") | Select-Object PSComputerName, DisplayName, StartName, PathName, StartMode| where DisplayName -Like "*xyz*" |Format-Table
I have till now managed to piece together the above to get the information I need from serveral servers, however now I want to format it so that I can collate information for each server in a format that I can display
for eg.
Server : ABC
RAM : 64 GB
Number of Processors : 8
Disk :
Table of disk Sizes Etc
Any pointers would be appreciated
With all these properties, you would get a nested object array, which probably is easiest to view in JSON format.
I have changed all Get-WmiObject into the newer and faster Get-CimInstance cmdlets below
$result = Get-Content "C:\Temp\Servers.txt" | ForEach-Object {
# create an ordered hashtable to store the results for each server
$pcinfo = [ordered]#{}
# System info
$data = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $_
$pcinfo['Computer'] = $data.PSComputerName
$pcinfo['Memory (RAM in GB)'] = '{0:N2}' -f ($data.TotalPhysicalMemory / 1GB)
# OS info
$data = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $_
$pcinfo['BuildNumber'] = $data.BuildNumber
$pcinfo['BuildType'] = $data.BuildType
$pcinfo['Caption'] = $data.Caption
$pcinfo['CodeSet'] = $data.CodeSet
$pcinfo['OSArchitecture'] = $data.OSArchitecture
$pcinfo['SystemDrive'] = $data.SystemDrive
$pcinfo['TotalVisibleMemorySize'] = $data.TotalVisibleMemorySize
$pcinfo['Version'] = $data.Version
# Product info (array of objects)
$pcinfo['Products'] = Get-CimInstance -ClassName Win32_Product -ComputerName $_ |
Select-Object Name, Version, Vendor, InstallDate
# Local fixed disk info (array of objects)
$pcinfo['FixedDrives'] = Get-CimInstance -ClassName Win32_LogicalDisk -ComputerName $_ -Filter 'DriveType=3' |
Sort-Object DeviceID |
Select-Object DriveType, DeviceID, VolumeName,
#{Name="Size";Expression={"{0:N2} GB" -f ($_.Size / 1GB)}},
#{Name="FreeSpace";Expression={"{0:N2} GB" -f ($_.FreeSpace / 1GB)}},
Compressed
# Services info (array of objects)
$pcinfo['Services'] = Get-CimInstance -ClassName Win32_Service -ComputerName $_ |
Where-Object { $_.DisplayName -like '*Adobe*' } |
Select-Object DisplayName, StartName, PathName, StartMode
# convert the hashtable to PSObject and output
[PsCustomObject]$pcinfo
}
# output the whole structure as JSON for easier reading and optionally save it to file
$result | ConvertTo-Json -Depth 3 # | Set-Content -Path 'Path\To\Output.json' -Force
**I tried n "n" '`n'
Blockquote
**
GC D:\code\ServerList.txt | % {
$Comp = $_
#write-output "server Information"
If (Test-Connection $Comp -Quiet){
$Luser = (Get-WmiObject -class win32_process -Filter
"Name='Explorer.exe'" -ComputerName $Comp | % {$_.GetOwner().User} |
Sort-Object -Unique) -join ","
$Mem = GWMI -Class win32_operatingsystem -computername $COMP
New-Object PSObject -Property #{
"ServerInfo" = ""
Server = $Comp
"CPU usage" = "$((GWMI -ComputerName $COMP win32_processor
| Measure-Object -property LoadPercentage -Average).Average) %"
"Memory usage" = "$("{0:N2}" -f
((($Mem.TotalVisibleMemorySize - $Mem.FreePhysicalMemory)*100)/
$Mem.TotalVisibleMemorySize)) %"
"Total FreeSpace" = "$("{0:N2}" -f ((Get-WmiObject -Class
win32_logicaldisk -ComputerName $COMP -Filter "DriveType = '3'" |
Measure-Object -property FreeSpace -Sum).Sum /1GB)) GB"
"DiskSpace" = "$("{0:N2}" -f ((Get-WmiObject -Class
win32_logicaldisk -ComputerName $COMP -Filter "DriveType = '3'" |
Measure-Object -property Size -Sum).Sum /1GB)) GB"
"Comment" = ""
"logged Users" = $Luser
}
}
Else{
"" | Select #{N="Server";E={$Comp}},"CPU usage","Memory usage","Total
FreeSpace","logged Users","DiskSpace"
}
}| Select "ServerInfo",Server,"logged Users","CPU usage","Memory
usage","Total FreeSpace" ,"DiskSpace", "Comment" |
Export-Csv "D:\code\Diskncpu.csv" -nti –Append
output
desired output
"`r`n"
Needs to be in double quotes I believe.
Use [System.Environment]::NewLine to add new lines anywhere you need.
Having said that I formatted your code for clarity and executed against an array
#("MECDEVAPP01","MECDEVAPP01")| % {
$Comp = $_
#write-output "server Information"
If (Test-Connection $Comp -Quiet){
$Luser = (Get-WmiObject -class win32_process -Filter "Name='Explorer.exe'" -ComputerName $Comp | % {$_.GetOwner().User} | Sort-Object -Unique) -join ","
$Mem = GWMI -Class win32_operatingsystem -computername $COMP
New-Object PSObject -Property #{
"ServerInfo" = ""
Server = $Comp
"CPU usage" = "$((GWMI -ComputerName $COMP win32_processor | Measure-Object -property LoadPercentage -Average).Average) %"
"Memory usage" = "$("{0:N2}" -f ((($Mem.TotalVisibleMemorySize - $Mem.FreePhysicalMemory)*100)/ $Mem.TotalVisibleMemorySize)) %"
"Total FreeSpace" = "$("{0:N2}" -f ((Get-WmiObject -Class win32_logicaldisk -ComputerName $COMP -Filter "DriveType = '3'" | Measure-Object -property FreeSpace -Sum).Sum /1GB)) GB"
"DiskSpace" = "$("{0:N2}" -f ((Get-WmiObject -Class win32_logicaldisk -ComputerName $COMP -Filter "DriveType = '3'" | Measure-Object -property Size -Sum).Sum /1GB)) GB"
"Comment" = ""
"logged Users" = $Luser
}
}
Else{
"" | Select #{N="Server";E={$Comp}},"CPU usage","Memory usage","Total FreeSpace","logged Users","DiskSpace"
}
}| Select "ServerInfo",Server,"logged Users","CPU usage","Memory usage","Total FreeSpace" ,"DiskSpace", "Comment"|
Export-Csv "C:\Users\asarafian\Downloads\Diskncpu.csv" -nti –Append
The csv file is like this
"ServerInfo","Server","logged Users","CPU usage","Memory usage","Total FreeSpace","DiskSpace","Comment"
"","MECDEVAPP01","","7 %","70,24 %","203,97 GB","278,36 GB",""
"","MECDEVAPP01","","0 %","70,25 %","203,97 GB","278,36 GB",""
which is what I would expect from a conversion of a recordset (that's what you are building with all those pipes) into a csv.
I you want to product a formatted text then you cant use csv or you need to combine elements of it.
Try using `r`n for a new line. It needs the new line and carriage return to work.
If I understand you correctly you want a row to appear with a newline character, but instead you get the `r`n litteral characters or anything you try to throw at it.
Minimal testcase I can come up with to reproduce this problem:
> function paste ($separator = '`r`n') {$($input) -join $separator}
> & { echo foo; echo bar; echo baz; } | paste
foo`r`nbar`r`nbaz
Expceted result was
foo
bar
baz
How do you get actual newlines as output instead of literal `r`n? Super simple, just use the suggested answer!
> function paste ($separator = "`r`n") {$($input) -join $separator}
> & { echo foo; echo bar; echo baz; } | paste
foo
bar
baz
Or, if you do not like magic strings:
function paste ($separator = [System.Environment]::NewLine) {$($input) -join $separator}
PS D:\Temp\specs\ProRail.TrackChanges.Specs.Features> & { echo foo; echo bar; echo baz; } | paste
foo
bar
baz
I wrote this quick script to retrieve information about a bunch of servers. When I run on my windows 7 (ps v2) host I get all the correct results. However, When I run on Server 2008 r2 (ps v2) I get System.Object[] for all the queries below. I have a bunch of other queries as well but they all work fine, just these ones I am getting this problem. Whats going on?
$ArrComputers = "localhost"
$OutputLog = ".\output.csv"
$NotRespondingLog = ".\notresponding.txt"
$ErrorActionPreference = "Stop"
Clear-Host
$data = ForEach ($Computer in $ArrComputers) {
try{
$ipAdd = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .)| select ipaddress
$MacAdd = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .)| Select MacAddress
$DefGateway = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .)| Select DefaultIPGateway
$DNSServ = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .)| Select DNSServerSearchOrder
$CPUname = (Get-WmiObject –class Win32_processor -ComputerName .)| Select name
$processorinfo = (Get-WmiObject –class Win32_processor -ComputerName .)| Select NumberOfCores
$processorinfo2 = (Get-WmiObject –class Win32_processor -ComputerName .)| Select NumberOfLogicalProcessors
$memory = Get-WMIObject -class Win32_PhysicalMemory -ComputerName $Computer |
Measure-Object -Property capacity -Sum |
select #{N="r"; E={[math]::round(($_.Sum / 1GB),2)}}
}catch{
$Computer | Out-File -FilePath $NotRespondingLog -Append -Encoding UTF8
continue
}
$props = #{
'IPAddress' = $ipAdd
'MacAddress' = $MacAdd
'DefaultIPGateway'= $DefGateway
'DNSServerSearchOrder' = $DNSServ
'cpuName' = $CPUname
'Cores' = $processorinfo
'logicalcores' = $processorinfo2
' Memory' = $memory
}
New-object -type PSCustomObject -Property $Props
}
$Data | export-csv -notypeinformation $outputlog
So the issue what you are facing: Powershell is returning the $data as Key=Value or hashtable format but as an object. So when you are inserting the same as CSV , then it is returning it as Object. So what you can do is you can convert the data to JSON format and you can insert the same. Else you can use Arraylist and insert all the values there. In that case it will accept the key-value pair mapping.
Hope it helps
I have removed the headers from the select query and created an array list with the custom object created in the loop and it will add each details from server to server and will append in the array list separately. I hope this helps you.
$ArrComputers = "localhost"
$OutputLog = ".\output.csv"
$NotRespondingLog = ".\notresponding.txt"
$ErrorActionPreference = "Stop"
Clear-Host
$Global:arraylist= New-Object System.Collections.ArrayList
$data = ForEach ($Computer in $ArrComputers) {
try{
$ipAdd = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName $Computer)| select ipaddress
$MacAdd = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName $Computer)| Select MacAddress
$DefGateway = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName $Computer)| Select DefaultIPGateway
$DNSServ = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName $Computer)| Select DNSServerSearchOrder
$CPUname = (Get-WmiObject –class Win32_processor -ComputerName $Computer)| Select name
$processorinfo = (Get-WmiObject –class Win32_processor -ComputerName $Computer)| Select NumberOfCores
$processorinfo2 = (Get-WmiObject –class Win32_processor -ComputerName $Computer)| Select NumberOfLogicalProcessors
$memory = Get-WMIObject -class Win32_PhysicalMemory -ComputerName $Computer |
Measure-Object -Property capacity -Sum |
select #{N="r"; E={[math]::round(($_.Sum / 1GB),2)}}
$props =[PSCustomObject]#{
'IPAddress' = $ipAdd.ipaddress[0]
'MacAddress' = $MacAdd.MacAddress
'DefaultIPGateway'= $DefGateway.DefaultIPGateway[0]
'DNSServerSearchOrder' = $DNSServ.DNSServerSearchOrder[0]
'cpuName' = $CPUname.name
'Cores' = $processorinfo.NumberOfCores
'logicalcores' = $processorinfo2.NumberOfLogicalProcessors
' Memory' = $memory.r
}
$arraylist.Add($props)
}catch{
$Computer | Out-File -FilePath $NotRespondingLog -Append -Encoding UTF8
continue
}
}
$arraylist | Export-Csv -NoTypeInformation $OutputLog -Force
Objective: How to extract server information?
For each server name listed in servers.txt, I would like to get the following information (in this format):
Server name, IP Address, OS name, Total Physical Memory, Processors, each drive letter and size, System Model
Comma separated and new line for each server.
Below is my PowerShell code. Can your guys give a hint on why this does not work? Also why I get an error with New-Object statement?
foreach ($ComputerName in (Get-Content -Path .\servers.txt)) {
$HashProps = #{
'tHostname' = Get-WmiObject Win32_Computersystem -ComputerName $ComputerName | Select-Object -ExpandProperty Name
'tIP' = [System.Net.Dns]::GetHostAddresses($computername)
'tOS' = Get-WmiObject -ComputerName $ComputerName -Class Win32_OperatingSystem | Select-Object -ExpandProperty Caption
'tMemory' = Get-WmiObject Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | foreach { "$("{0:n2}" -f ( $_.Sum/1GB ) )" }
'tcpu' = Get-WmiObject Win32_processor | Select-Object name, numberofcores
'tDisks' = Get-WmiObject Win32_LogicalDisk | foreach { "$($_.DeviceID) $("{0:n2}" -f ( $_.Size/ 1GB ) )" }
'tsysmodel' = Get-Wmiobject Win32_computersystem | Select-Object model
}
New-Object -TypeName psObject -Property $HashProps |
ConvertTo-Csv -NoTypeInformation | Out-File -Append .\output.csv
}
I am open for a other approach, if this is easier.
Have you verified that each of those lines actually return what you want?
I just threw this into the ISE and it works fine:
$f = gwmi win32_computersystem | select name,model,totalphysicalmemory
$hash = #{
'name' = $f.name
'model' = $f.model
'memory' = $("{0:n2}" -f ( $f.totalphysicalmemory/1GB ) )
}
New-Object -TypeName psobject -Property $hash | ConvertTo-Csv -NoTypeInformation | Out-File -Append .\test.csv
Also, if you want the properties to appear in a specific order in the CSV, it will take some additional magic, otherwise they're put in alphabetically.
A little bit pimped, maybe this will help you:
$Servers = Foreach ($ComputerName in (Get-Content -Path .\Servers.txt)) {
$CS = Get-WmiObject Win32_ComputerSystem -ComputerName $ComputerName
$OS = Get-WmiObject Win32_OperatingSystem -ComputerName $ComputerName
$PM = Get-WmiObject Win32_PhysicalMemory -ComputerName $ComputerName
$PR = Get-WmiObject Win32_processor -ComputerName $ComputerName
$LD = Get-WmiObject Win32_LogicalDisk -ComputerName $ComputerName
$IP = [System.Net.Dns]::GetHostAddresses($ComputerName)
[PSCustomObject]#{
ServerName = $CS | Select-Object -ExpandProperty Name
IPAddress = $IP | Select-Object -ExpandProperty IPAddressToString
OS = $OS | Select-Object -ExpandProperty Caption
Memory = $PM | Measure-Object -Property Capacity -Sum | foreach { "$("{0:n2}" -f ( $_.Sum/1GB ) )" }
CPU = $PR | Select-Object Name, NumberOfCores
Disks = $LD | foreach { "$($_.DeviceID) $("{0:n2}" -f ( $_.Size/ 1GB ) )" }
Model = $CS | Select-Object -ExpandProperty Model
}
}
$File = Join-Path $env:TEMP 'Ouptut.csv'
$Servers | Export-Csv -Path $File -NoTypeInformation -Delimiter ';'
Start-Process $File
I have written a for each file which stores the BIOS information of the systems in a network and the result is being displayed on my console but I want them to be in a HTML file in an order.
Code:
$arrComputers = get-Content -Path "C:\Computers.txt"
foreach ($strComputer in $arrComputers)
{
$colItems = get-wmiobject -class "Win32_BIOS" -namespace "root\CIMV2" `
-computername $strComputer
foreach ($objItem in $colItems)
{
write-host "Computer Name: " $strComputer
write-host "BIOS Version: " $objItem.BIOSVersion
}
$colItems1 = get-wmiobject -class Win32_logicaldisk -Filter "DeviceID = 'C:'" -computername $strComputer
foreach ($objItem1 in $colItems1)
{
$e=$objItem1.freeSpace/1GB
write-host "Total Space: " $e
}
$colItems4 = Get-WMIObject -class Win32_PhysicalMemory -computername $strComputer
$colItems5=$colItems4 | Measure-Object -Property capacity -Sum
foreach ($objItem4 in $colItems5)
{
$e4=$colItems5.Sum/1GB
write-host "Memory : " $e4
}
}
Can you please help me in saving all the above data in HTML
You need to look at the ConvertTo-Html cmdlet.
Get-WmiObject -Class Win32_BIOS -ComputerName localhost,$env:COMPUTERNAME |
Select PSComputerName,Version,SerialNumber |
ConvertTo-Html |
Out-File c:\test3.html
Another method based on OPs update:
$arrComputers = get-Content -Path "C:\Computers.txt"
$arrComputers | ForEach-Object { Get-WMIObject -Class Win32_BIOS -ComputerName $_ } |
Select PSComputerName, Version, Manufacturer |
ConvertTo-Html |
Out-File C:\test4.html