Output server information to Excel file - excel

I've a PowerShell script that can generate server status info to me. My problem now is I want to output result to an Excel file.
PowerShell code:
function getwmiinfo ($svr) {
gwmi -Query "select * from Win32_ComputerSystem" -ComputerName $svr |
select Name, Model, Manufacturer, Description, DNSHostName, Domain,
DomainRole, PartOfDomain, NumberOfProcessors, SystemType,
TotalPhysicalMemory, UserName, Workgroup |
Format-Table -Property * -Autosize | Out-String -Width 10000
gwmi -Query "select * from Win32_OperatingSystem" -ComputerName $svr |
select Name, Version, FreePhysicalMemory, OSLanguage, OSProductSuite,
OSType, ServicePackMajorVersion, ServicePackMinorVersion |
Format-Table -Property * -Autosize | Out-String -Width 10000
gwmi -Query "select * from Win32_PhysicalMemory" -ComputerName $svr |
select Name, Capacity, DeviceLocator, Tag |
Format-Table -Autosize
gwmi -Query "select * from Win32_LogicalDisk where DriveType=3" -ComputerName $svr |
select Name, FreeSpace, Size |
Format-Table -Autosize
}
$servers = Get-Content 'servers.txt'
foreach ($server in $servers) {
$results = gwmi -query "select StatusCode from Win32_PingStatus where Address = '$server'"
$responds = $false
foreach ($result in $results) {
if ($result.statuscode -eq 0) {
$responds = $true
break
}
}
if ($responds) {
getwmiinfo $server
} else {
Write-Output "$server does not respond"
}
}
Output to Excel:

You can use Export-Csv (Export-Csv file path -NoTypeInformation). This is the command.
If you want to use array then you will have to define that. You can check this question.
E.g. $variable | Export-Csv c:\output.csv -notypeinformtion

Related

Powershell Computer information query export to excel

im trying to take a list of computers and pull information from them and export it into an excel sheet where i have all information of the systems per row. im trying to get information like:
Computername
OS
BIOS
Last boot
Etc
the code i wrote:
$computers = Get-Content "C:\example\Computers.txt)"
$OSinfo = Get-WmiObject Win32_OperatingSystem -ComputerName $computers | Select PSComputerName, Caption, OSArchitecture, Version, BuildNumber
$BIOSinfo = Get-WmiObject -Class Win32_BIOS -ComputerName $computers | Select-Object PSComputerName, Manufacturer, SerialNumber, SMBIOSBIOSVersion
$lastboot = Get-CimInstance win32_operatingsystem -ComputerName $computers | select csname, lastbootuptime
$objects +=$OSinfo +=$BIOSinfo +=$lastboot
$objects | Export-csv -Path "C:\example\output.csv"
however, i cant figure out how to put all this information into one spreadsheet tab. i also cant figure out how to tell the script if it cant ping or find it, to just say "offline"
This should work for you:
$computers = Get-Content "C:\example\Computers.txt"
# Define the properties we want to select from each query
$osColumns = 'PSComputerName', 'Caption', 'OSArchitecture', 'Version', 'BuildNumber'
$biosColumns = 'PSComputerName', 'Manufacturer', 'SerialNumber', 'SMBIOSBIOSVersion'
$lastbootColumns = 'csname', 'lastbootuptime'
# Obtain the desired information from Wmi/Cim
$OSinfo = Get-WmiObject Win32_OperatingSystem -ComputerName $computers | Select-Object $osColumns
$BIOSinfo = Get-WmiObject -Class Win32_BIOS -ComputerName $computers | Select-Object $biosColumns
$lastboot = Get-CimInstance win32_operatingsystem -ComputerName $computers | Select-Object $lastbootColumns
# Iterate over the computers and collect the computer-specific information
$computerInfo = foreach( $computer in $computers ) {
$thisOSInfo = $OSInfo | Where-Object { $_.PSComputerName -eq $computer }
$thisBIOSInfo = $BIOSinfo | Where-Object { $_.PSComputerName -eq $computer }
$thisLastboot = $lastboot | Where-Object { $_.csname -eq $computer }
# This row object will be returned as a PSCustomObject for export
$row = #{}
foreach( $prop in #( $thisOSInfo.psobject.Properties.Name ) ) {
if( $prop -in $osColumns ) {
$row[$prop] = $thisOSInfo.$prop
}
}
foreach( $prop in #( $thisBIOSInfo.psobject.Properties.Name ) ) {
if( $prop -in $biosColumns ) {
$row[$prop] = $thisBIOSInfo.$prop
}
}
foreach( $prop in #( $thisLastboot.psobject.Properties.Name ) ) {
if( $prop -in $lastbootColumns ) {
$row[$prop] = $thisLastboot.$prop
}
}
[PSCustomObject]$row
}
$computerInfo | Export-Csv -NoTypeInformation \path\to\report.csv
The way this works:
Well-define the columns we want from each query. We'll use those later to make sure we only grab properties we want from the resulting query responses. Note that Get-CimInstance will have the csname property instead of PSComputerName.
Query WMI classes for information on known computers, store each response in its own variable.
Iterate over each computer queried, building that row of information from each query response.
Only add the query property if it exists in the corresponding *Columns variable. This is less necessary for your code but becomes necessary when exporting some other, non-WMI/Cim objects, or if you don't use Select-Object earlier, to reduce noise.
Each row is defined as a hastable for ease of modification, then converted to a PSCustomObject to it behaves more like an immutable object upon return. This is necessary for the output of Export-Csv to output the way you want.
Export the computer information with Export-Csv to a CSV file, which is now an array of PSCustomObjects where each row should be a single computer you've queried.

Powershell export CSV looks weird

I have an issue with my CSV export to Excel with powershell. When I import it looks like pretty bad and I can't find any information that helps me to solve it.
Here I attach an image of the import and the code. I see other CSV imports and it looks normal with its categories spaced by rows in Excel, but I don't know how to do it.
Image of my workbook
$Computers = Get-ADComputer -Filter {OperatingSystem -like "*Server*"} -Properties OperatingSystem | Select-Object -ExpandProperty Name
Foreach($computer in $computers){
if(!(Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
{write-host "cannot reach $computer offline" -f red}
else {
$outtbl = #()
Try{
$sr=Get-WmiObject win32_bios -ComputerName $Computer -ErrorAction Stop
$Xr=Get-WmiObject –class Win32_processor -ComputerName $computer -ErrorAction Stop
$ld=get-adcomputer $computer -properties Name,Lastlogondate,operatingsystem,ipv4Address,enabled,description,DistinguishedName -ErrorAction Stop
$r="{0} GB" -f ((Get-WmiObject Win32_PhysicalMemory -ComputerName $computer |Measure-Object Capacity -Sum).Sum / 1GB)
$x = gwmi win32_computersystem -ComputerName $computer |select #{Name = "Type";Expression = {if (($_.pcsystemtype -eq '2') )
{'Laptop'} Else {'Desktop Or Other something else'}}},Manufacturer,#{Name = "Model";Expression = {if (($_.model -eq "$null") ) {'Virtual'} Else {$_.model}}},username -ErrorAction Stop
$t= New-Object PSObject -Property #{
serialnumber = $sr.serialnumber
computername = $ld.name
Ipaddress=$ld.ipv4Address
Enabled=$ld.Enabled
Description=$ld.description
Ou=$ld.DistinguishedName.split(',')[1].split('=')[1]
Type = $x.type
Manufacturer=$x.Manufacturer
Model=$x.Model
Ram=$R
ProcessorName=($xr.name | Out-String).Trim()
NumberOfCores=($xr.NumberOfCores | Out-String).Trim()
NumberOfLogicalProcessors=($xr.NumberOfLogicalProcessors | Out-String).Trim()
Addresswidth=($xr.Addresswidth | Out-String).Trim()
Operatingsystem=$ld.operatingsystem
Lastlogondate=$ld.lastlogondate
LoggedinUser=$x.username
}
$outtbl += $t
}
catch [Exception]
{
"Error communicating with $computer, skipping to next"
}
$outtbl | select Computername,enabled,description,ipAddress,Ou,Type,Serialnumber,Manufacturer,Model,Ram,ProcessorName,NumberOfCores,NumberOfLogicalProcessors,Addresswidth,Operatingsystem,loggedinuser,Lastlogondate |export-csv -Append C:\temp\VerynewAdinventory.csv -nti
}
}
As commented, your locale computer uses a different delimiter character that Export-Csv by default uses (that is the comma).
You can check what character your computer (and thus your Excel) uses like this:
[cultureinfo]::CurrentCulture.TextInfo.ListSeparator
To use Export-Csv in a way that you can simply double-click the output csv file to open in Excel, you need to either append switch -UseCulture to it, OR tell it what the delimiter should be if not a comma by appending parameter -Delimiter followed by the character you got from the above code line.
That said, your code does not produce the full table, because the export to the csv file is in the wrong place. As Palle Due commented, you could have seen that if you would indent your code properly.
Also, I would advise to use more self-describing variable names, so not $r or $x, but $memory and $machine for instance.
Nowadays, you should use Get-CimInstance rather than Get-WmiObject
AND adding to an array with += should be avoided as it is both time and memory consuming. (on every addition to an array, which is of fixed size, the entire array has to be rebuilt in memory).
Your code revised:
# set the $ErrorActionPreference to Stop, so you don't have to add -ErrorAction Stop everywhere in the script
# remember the currens value, so you can restore that afterwards.
$oldErrorPref = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
# get an array of computers, gathering all properties you need
$computers = Get-ADComputer -Filter "OperatingSystem -like '*Server*'" -Properties OperatingSystem, LastLogonDate, IPv4Address, Description
$result = foreach ($computer in $computers) {
$serverName = $computer.Name
if(!(Test-Connection -ComputerName $serverName -BufferSize 16 -Count 1 -ErrorAction SilentlyContinue -Quiet)) {
Write-Host "cannot reach $serverName offline" -ForegroundColor Red
continue # skip this computer and proceed with the next one
}
try {
# instead of Get-WmiObject, nowadays you should use Get-CimInstance
$bios = Get-WmiObject -Class Win32_bios -ComputerName $serverName
$processor = Get-WmiObject -Class Win32_Processor -ComputerName $serverName
$memory = Get-WmiObject -Class Win32_PhysicalMemory -ComputerName $serverName
$disks = Get-WmiObject -Class Win32_LogicalDisk -ComputerName $serverName
$machine = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $serverName |
Select-Object #{Name = "Type"; Expression = {
if ($_.pcsystemtype -eq '2') {'Laptop'} else {'Desktop Or Other something else'}}
},
Manufacturer,
#{Name = "Model"; Expression = {
if (!$_.model) {'Virtual'} else {$_.model}}
},
UserName
# output an object to be collected in variable $result
# put the properties in the order you would like in the output
[PsCustomObject] #{
ComputerName = $serverName
Enabled = $computer.Enabled
Description = $computer.description
IpAddress = $computer.IPv4Address
Ou = $computer.DistinguishedName.split(',')[1].split('=')[1]
Type = $machine.type
SerialNumber = $bios.serialnumber
Manufacturer = $machine.Manufacturer
Model = $machine.Model
Ram = '{0} GB' -f (($memory | Measure-Object Capacity -Sum).Sum / 1GB)
ProcessorName = $processor.Name
NumberOfCores = $processor.NumberOfCores
NumberOfLogicalProcessors = $processor.NumberOfLogicalProcessors
Addresswidth = $processor.Addresswidth
OperatingSystem = $computer.OperatingSystem
# {0:N2} returns the number formatted with two decimals
TotalFreeDiskSpace = '{0:N2} GB' -f (($disks | Measure-Object FreeSpace -Sum).Sum / 1GB)
LoggedInUser = $machine.UserName
Lastlogondate = $computer.LastLogonDate
}
}
catch {
Write-Warning "Error communicating with computer $serverName, skipping to next"
}
}
# restore the ErrorActionPreference to its former value
$ErrorActionPreference = $oldErrorPref
# output the completed array in a CSV file
# (using the delimiter characer your local machine has set as ListSeparator)
$result | Export-Csv -Path 'C:\temp\VerynewAdinventory.csv' -UseCulture -NoTypeInformation

Powershell, how obtain a csv by column with a pscustomobject or ordered?

Being a beginner in Powershell, I have a problem that I can't solve. I get the average of different CSV files as a string with the following code:
# recovery of the list of csv files present in the folder "folder_1".
$files=(Get-ChildItem -path "C:\folder_1\" -Recurse -Include *.csv)
#loop to read each file and average the variables "PRESS_CELL" and "PRESS_DELTA
foreach($file in $files){
$varTemp = #((Get-Content $file | ConvertFrom-Csv | Measure-Object "PRESS_CELL","PRESS_DELTA" -Average | Export-Csv -Path "C:\folder_1\Alias.csv" -NoTypeInformation -Append))
Write-Host $varTemp
}
#added an increment to sort the data (averages)
$vartemp2 = Import-CSV "C:\folder_1\Alias.csv" | Select *,LINENUMBER | ForEach-Object -Begin { $Line = 1 } {
$_.LineNumber = $Line++
$_
} | Export-CSV "C:\folder_1\Alias2.csv" -NoTypeInformation
Write-Host $vartemp2
# sort data by "property" and by "LINENUMBER"
$vartemp3 = Import-Csv "C:\folder_1\Alias2.csv"
$vartemp3 | % { $_.LINENUMBER = [int]$_.LINENUMBER }
$vartemp3 | Sort-Object -Property #{ Expression = 'Property'; Ascending = $true }, #{ Expression = 'LINENUMBER'; Ascending = $true } |
Format-Table -Property "Average","Property","LINENUMBER"
# groups the values obtained in a table/customobject and export it to csv by column ?
$fields = [ordered]#{
PRESS_CELL = $vartemp3 | ? property -like *PRESS_CELL* | Select -ExpandProperty Average
PRESS_DELTA = $vartemp3 | ? property -like *PRESS_DELTA* |Select -ExpandProperty Average
}
$fields | export-csv C:\1_ICOS_data\Alias4.csv -Append ##DOESN'T WORK
[result][1]
However, I would like to export the result as a CSV table (1 column per result with PRESS_CELL and PRESS_DELTA as headers. When I use the pipeline :
| export-csv C:\temp\alias.csv -Append
I get a result :
With "ordered"
"System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKeyValueCollection","System.Collections.Specialized.OrderedDictionary+OrderedDictionaryKeyValueCollection","False","System.Object","False"
And with pscustomobject :
System.Object[],"System.Object[]"
Add -NoTypeInformation to export-csv command like that
$fields = [ordered]#{
PRESS_CELL = $vartemp3 | ? property -like *PRESS_CELL* | Select -ExpandProperty Average
PRESS_DELTA = $vartemp3 | ? property -like *PRESS_DELTA* |Select -ExpandProperty Average
}
#Or:
$fields = [pscustomobject]#{
PRESS_CELL = $vartemp3 | ? property -like *PRESS_CELL* | Select -ExpandProperty Average
PRESS_DELTA = $vartemp3 | ? property -like *PRESS_DELTA* |Select -ExpandProperty Average }
$fields |export-csv "c:\fields.csv" -Append -NoTypeInformation

Limit the Number of Simultaneously Running Threads

I have a script that does a ping sweep on my work environment and I am trying to limit the number of simultaneously running threads. I have been playing around with many of the solutions online but I cant seem to make any progress. Any help will be appreciated.
$scriptblock = {
Param($comp)
IF (Test-Connection -computername $comp -Quiet -Count 1) {
[bool]$responding = $true
}
else {
Write-Host "***$comp ERROR -Not responding***"
$responding = $false
}
New-Object psobject -Property #{'Computer Name' = $comp;
'Online' = $responding;
}
}
$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('MM-dd-yyyy_hh-mm-ss')
$location = Get-Location
$comps = (get-content -path $location'\hostnames.txt').Trim()
$comps | ForEach-Object {Start-Job -Scriptblock $scriptblock -ArgumentList $_ | Out-Null}
Get-Job | Wait-Job | Receive-Job | Select-Object 'Computer Name','Online'`
-ExcludeProperty RunspaceId, PSComputerName, PSShowComputerName | Export-csv -NoTypeInformation "$location\PingTest-$CurrentDate.csv"

Can not convert output to string

I cannot format this command to string. The code below returns $r as an empty string. Why?
$f = gwmi -ComputerName PCname -Class Win32_Process -Filter "name='process.exe'"|
select {$_.WorkingSetSize/1MB}|fl
$r = $f.ToString()
If you check the object type returned by Format-List you will see that it is an array of System.Object.
$f = gwmi -ComputerName PCname -Class Win32_Process -Filter "name='process.exe'"| `
select {$_.WorkingSetSize/1MB}|fl
$r | get-member
If you just need the values of working set, try this:
gwmi -ComputerName PCname -Class Win32_Process -Filter "name='process.exe'" | `
select #{label='WorkingSetSize';expression={$_.WorkingSetSize/1MB}}| `
select -expandproperty WorkingSetSize
Format-List produces an array of strings, not a single string, so $f.ToString() should give you System.Object[]. To convert an array to a single string you can pipe it into the Out-String cmdlet:
$f = gwmi -ComputerName PCname -Class Win32_Process -Filter "name='process.exe'" |
select {$_.WorkingSetSize/1MB} | fl
$g = $f | Out-String
However, as mentioned above, you should at least get System.Object[], not an empty string, so double-check the value of $f.
What I find is that -Filter "name='process.exe'" does not work for me. So I substituted
| where {$_.name -match "Process"}
This is my result, I also substituted LocalHost for PCname and removed |fl
$r = gwmi -ComputerName localhost -Class Win32_Process | where {$_.name -match "Process"} |
select #{label='WorkingSetSize';expression={$_.WorkingSetSize/1MB}} |
select -expandproperty WorkingSetSize
$r.ToString()

Resources