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.
Related
I am trying to display data within an Excel document where Column A displays the server name and column B displays the .NET version. I'm running into an issue exporting to a .csv because it says that the file path does not exist. I would like some guidance on how I can resolve that issue and how I can display data on the two columns within Excel.
$Servers =
(
"test"
)
foreach ($Server in $Servers)
{
Invoke-Command -ComputerName $Server -ScriptBlock {
Write-Output "$(hostname)"
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name Version,Release -EA 0 | where { $_.PSChildName -match '^(?!S)\p{L}'} | select PSChildName, Version, Release | Select -ExpandProperty Version | Sort-Object Version | Export-Csv -Path C:\Users\User\Desktop\example.csv
}
The main issue is that you're using Export-Csv on the remote hosts since it is inside the Invoke-Command script block, and the likeable error is because the path you are using as export doesn't exist on those hosts.
It's also worth noting that Invoke-Command can run in parallel, -ComputerName as well as -Session can take an array, this removes the need for the foreach loop as well as it is much faster / efficient.
Invoke-Command -ComputerName $servers -ScriptBlock {
Write-Host "Working on $($env:COMPUTERNAME)..."
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
Get-ItemProperty -Name Version, Release -EA 0 |
ForEach-Object {
if($_.PSChildName -notmatch '^(?!S)\p{L}') {
return # skip this
}
[pscustomobject]#{
HostName = $env:COMPUTERNAME
Version = $_.Version
}
} | Sort-Object Version
} -HideComputerName | Select-Object * -ExcludeProperty RunspaceID |
Export-Csv -Path C:\Users\User\Desktop\example.csv -NoTypeInformation
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
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
What im trying to do is the following:
Im getting a list of all VM`s that have some set values such as being in use and NOT having Azure Benefits turned on.
What i have is that i made a tiny script to get all machines within an subscription and select on the basis mentioned above.
What i want to do with that output is do the command Update-azureVM in bulk.
Could someone help me with this ? do i need to export the values to an excel and use that sheet to do a bulk update-AzureVM
here is the code that i have setup at the moment:
$returnObj = #()
$VMs=Get-AzVm -status
foreach ($VM in $VMs)
{
$obj = New-Object psobject -Property #{
"VmSize" = $VM.HardwareProfile.VmSize;
"VmName" = $vm.Name;
"PowerState" = $vm.PowerState;
"License_Type" = $vm.LicenseType;
}
$returnObj += $obj | select VmSize, VmName, PowerState, License_Type
}
$returnObj |
Where-Object{$_.PowerState -ne "VM deallocated"} |
Where-Object{$_.License_Type -ne "Windows_Server"} |
Where-Object{$_.License_Type -ne "Windows_Client"} |
Export-Csv C:\temp\freek.csv
Thank you all in advance!
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