Ordering Table Columns - Powershell [duplicate] - powershell

This question already has answers here:
Change order of columns in the object
(5 answers)
Closed 5 years ago.
Good Afternoon,
I have the following script to generate a table as part of a html report that I have:
(import-csv "C:\AutoTasks\server.txt" |
% {new-object psobject -property #{
"Asset Number"=$_.Computer;
"Region"=$_.Description;
"Online Status"=(test-connection -computername $_.Computer -quiet -count 1);
"Online Since"= Try {(([Management.ManagementDateTimeConverter]::ToDateTime((gwmi Win32_OperatingSystem -ComputerName $_.Computer -ErrorAction Stop).LastBootUpTime)))} Catch {"Offline"} ;
"Service"=((Get-Service -ComputerName $_.Computer | Where-Object {$_.DisplayName -eq "ServiceName"}).Status);
"Disk Size (GB)" = ([Math]::Round(((get-WmiObject win32_logicaldisk -Computername $_.Computer -Filter $_.Drive).size)/1Gb,2));
"Free Disk Space (GB)" = ([Math]::Round(((get-WmiObject win32_logicaldisk -Computername $_.Computer -Filter $_.Drive).freespace)/1Gb,2));
"Free Disk Space %" = ([Math]::Round(100*(([Math]::Round(((get-WmiObject win32_logicaldisk -Computername $_.Computer -Filter $_.Drive).freespace)/1Gb,2)) / ([Math]::Round(((get-WmiObject win32_logicaldisk -Computername $_.Computer -Filter $_.Drive).size)/1Gb,2))),2))
}} | ConvertTo-HTML -as Table -Fragment -PreContent "<h2>Backup Machines</h2>" | Out-String)
It does everything I need.
However, my issue is with the column ordering. It doesn't display in the column order I've listed, and there is seemingly no logic behind the order it offers.
Any ideas how I can specify the order, am I missing a format-table statement somewhere? My searches are drawing a blank.

In PowerShell 3.0 and newer, you can use the [ordered] attribute on a hashtable literal to indicate that you want an ordered dictionary instead:
(import-csv "C:\AutoTasks\server.txt" |
% {new-object psobject -property $([ordered]#{
"Asset Number"=$_.Computer;
"Region"=$_.Description;
"Online Status"=(test-connection -computername $_.Computer -quiet -count 1);
"Online Since"= Try {(([Management.ManagementDateTimeConverter]::ToDateTime((gwmi Win32_OperatingSystem -ComputerName $_.Computer -ErrorAction Stop).LastBootUpTime)))} Catch {"Offline"} ;
"Service"=((Get-Service -ComputerName $_.Computer | Where-Object {$_.DisplayName -eq "ServiceName"}).Status);
"Disk Size (GB)" = ([Math]::Round(((get-WmiObject win32_logicaldisk -Computername $_.Computer -Filter $_.Drive).size)/1Gb,2));
"Free Disk Space (GB)" = ([Math]::Round(((get-WmiObject win32_logicaldisk -Computername $_.Computer -Filter $_.Drive).freespace)/1Gb,2));
"Free Disk Space %" = ([Math]::Round(100*(([Math]::Round(((get-WmiObject win32_logicaldisk -Computername $_.Computer -Filter $_.Drive).freespace)/1Gb,2)) / ([Math]::Round(((get-WmiObject win32_logicaldisk -Computername $_.Computer -Filter $_.Drive).size)/1Gb,2))),2))
})} | ConvertTo-HTML -as Table -Fragment -PreContent "<h2>Backup Machines</h2>" | Out-String)

Related

Formatting multiple result sets together in powershell

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

Not able to format output as CSV [duplicate]

This question already has an answer here:
Get WMI Data From Multiple Computers and Export to CSV
(1 answer)
Closed 3 years ago.
Am not able to convert PS output to CSV format using echo function. I need to collect hardware information about multiple servers and got this script from internet. I modified it to collect only the necessary information such as Computername,HDD space, CPU details and RAM.
Below is my code:
$ArrComputers = "PC17"
Clear-Host
foreach ($Computer in $ArrComputers) {
$computerSystemRam = Get-WmiObject Win32_ComputerSystem -Computer $Computer |
select #{n="Ram";e={[math]::Round($_.TotalPhysicalMemory/1GB,2)}} |
FT -HideTableHeaders -AutoSize
$computerCPU = Get-WmiObject Win32_Processor -Computer $Computer |
select Name |
FT -HideTableHeaders
$computerCPUCores = Get-WmiObject Win32_Processor -Computer $Computer |
select NumberOfLogicalProcessors |
FT -HideTableHeaders -AutoSize
$computerC = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'C:'" -ComputerName $Computer |
select #{n="Size";e={[math]::Round($_.Size/1GB,2)}} |
FT -HideTableHeaders -AutoSize
$computerD = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'D:'" -ComputerName $Computer |
select #{n="Size";e={[math]::Round($_.Size/1GB,2)}} |
FT -HideTableHeaders -AutoSize
$computerE = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'E:'" -ComputerName $Computer |
select #{n="Size";e={[math]::Round($_.Size/1GB,2)}} |
FT -HideTableHeaders -AutoSize
echo $computer,$computerC,$computerD,$computerE,$computerSystemRam,$computerCPU,$computerCPUCores
}
and my output is coming as
PC17
99.9
12
537.11
15.98
Intel(R) Xeon(R) CPU E5-2630 0 # 2.30GHz
12
What I need is to get this outputs as a comma separated value like below
PC17,99.9,12,537.11,15.98,Intel(R) Xeon(R) CPU E5-2630 0 # 2.30GHz,12
so that I can open it in Excel. Please let me know what the problem here is? Or any other alternative solution to so as to get the output as .csv.
Remove the Format-Table, use ExpandProperty and choose the right property from the array,
Also, I used -f to format the csv, see the differences:
foreach ($Computer in $ArrComputers)
{
$computerSystemRam = get-wmiobject Win32_ComputerSystem -Computer $Computer | select #{n="Ram";e={[math]::Round($_.TotalPhysicalMemory/1GB,2)}}
$computerCPU = get-wmiobject Win32_Processor -Computer $Computer | select -ExpandProperty Name
$computerCPUCores = get-wmiobject Win32_Processor -Computer $Computer | select -ExpandProperty NumberOfLogicalProcessors
$computerC = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'C:'" -ComputerName $Computer | select #{n="Size";e={[math]::Round($_.Size/1GB,2)}}
$computerD = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'D:'" -ComputerName $Computer | select #{n="Size";e={[math]::Round($_.Size/1GB,2)}}
$computerE = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID= 'E:'" -ComputerName $Computer | select #{n="Size";e={[math]::Round($_.Size/1GB,2)}}
"{0},{1},{2},{3},{4},{5},{6}" -f $computer,$computerC.Size,$computerD.Size,$computerE.Size,$computerSystemRam.Ram,$computerCPU,$computerCPUCores
}

Get computer OS version

This script is working fine to get the OS version. I need to know who to get only Microsoft Windows 10 Pro in the result
$Computers = Get-Content C:\computerlist
Foreach($Computer in $Computers)
{
Get-WmiObject Win32_OperatingSystem -ComputerName $Computer -ErrorAction SilentlyContinue | Select-Object CSName, Caption | sort CSName
}
I'm not sure if I understandy you correctly, but I think you need Where-Object:
$Computers = Get-Content C:\computerlist
Foreach($Computer in $Computers)
{
Get-WmiObject Win32_OperatingSystem -ComputerName $Computer -ErrorAction SilentlyContinue | Select-Object CSName, Caption | where Caption -eq "Microsoft Windows 10 Pro" | sort CSName
}
If you want just the Caption value, use Select-Object -ExpandProperty Caption:
foreach($Computer in $Computers)
{
Get-WmiObject Win32_OperatingSystem -ComputerName $Computer -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Caption
}

How to store data from foreach function in HTML file in powershell and get Physicall ram

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

Converting from bytes into gigabytes

I am using following script to get disk space audit in our enterprise environment.
Everything works fine except that I don't know how to get those values presented in GB/MB.
Any idea?
$Computers = Get-Content -Path D:\DISKSPACE_audit\Servers.txt
Get-WmiObject Win32_LogicalDisk -ComputerName $Computers | Where-Object {
$_.DriveType -eq 3
} | Select-Object SystemName,DeviceID,FreeSpace,Size
Divide the value by 1GB (or 1MB):
$Computers = Get-Content "D:\DISKSPACE_audit\Servers.txt"
Get-WmiObject Win32_LogicalDisk -Computer $Computers -Filter 'DriveType = 3' |
Select-Object SystemName, DeviceID,
#{n='FreeSpace';e={[int]($_.FreeSpace/1GB)}},
#{n='Size';e={[int]($_.Size/1GB)}}