How to export output of batch file/Powershell Script in a Excel Spreadsheet - excel

I have been asked to go around the entire building and document the serial numbers, and system information on all of the PC's in the network. As I was doing it I realized that I could of just wrote a batch file or Powershell Script to do this for me. I typed in the command "wmic bios get serialnumber" and it gave me the serial number for my machine. Is there a way to Get all of the information such as the processor, memory, ip address, and serial number and output it in a excel spreadsheet ? If it can only be exported in a text file that is fine. I would like to save it on my server. I don't know how I can save it all to one text file. I realize that I could have the batch file make a text file of its own with the >> %COMPUTERNAME%.txt command.
Any help or suggestions would be great!
Thanks!
Get-WmiObject win32_processor | Findstr ('Name') | Format-List
$env:COMPUTERNAME | Format-List
wmic bios get serialnumber /Format
Get-WmiObject -Class Win32_ComputerSystem | Findstr ('Model') | Format-List
Get-WmiObject -Class Win32_ComputerSystem | Findstr ('Manufacturer') | Format-List
Get-WmiObject -Class Win32_ComputerSystem | Findstr ('Name') | Format-List
(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim() | Format-List
Export-CSV -Path C:\Users\ars001\%COMPUTERNAME%.csv | Format-List

Ok, you evidently put in some effort to get the commands to at least gather the info and what classes you'd need for what details, so I'll give you this much...
$Computers = Get-Content C:\Path\To\ComputerList.txt
[array]$Results = $Record = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $PC | select Model,Manufacturer,Name,TotalPhysicalMemory
$Results[0] | Add-Member 'Processor' $(Get-WmiObject win32_processor -ComputerName $PC | % Name)
$Results[0] | Add-Member 'SerialNumber' $(Get-WmiObject bios -ComputerName $PC |% serialnumber)
ForEach($PC in $Computers){
If(!(Test-Connection $PC -Quiet) -or $PC -eq $env:COMPUTERNAME){Continue}
$Record = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $PC | select Model,Manufacturer,Name,TotalPhysicalMemory
$Record | Add-Member 'Processor' $(Get-WmiObject win32_processor -ComputerName $PC | % Name)
$Results += $Record | Add-Member 'SerialNumber' $(Get-WmiObject bios -ComputerName $PC |% serialnumber) -PassThru
}
$Results | Export-Csv c:\Path\To\Output.csv -NoTypeInformation
Then you just need to edit the paths, and have a list of computers saved as a text file. If you have the AD module installed you can query AD for that info instead.

Related

PowerShell export "Get-volume" to excel/csv

I used the below one it gives somewhat different in excel ,please help me on this
#Disk Space
Get-Volume
$results = Get-Volume | Export-Csv -Path C:\temp\software1.csv
Note: I need health check , Drive Name, Free space , size, disk type in excel
Thanks in advance friends :)
Generally speaking, when you run a powershell command it only shows what sections are deemed as important. If you take the same command and pipe it to format-list (or "ft" for short) you will get everything.
Get-Volume | ft
When exporting it exports everything.
Also, you need to add the paramater -NoTypeInformation to get rid of the first row.
To only get certain values, you will just pipe it using select.. something like this:
Get-Volume | select HealthStatus, DriveLetter, SizeRemaining,DriveType | Export-Csv -NoTypeInformation -Path C:\temp\software1.csv
Also, there is no need to do $results = get-volume... This pushes the output into the variable $results. This would be applicable if you wanted to recall the variable later. So, you could also do something like this..
$results = Get-Volume
$results | select HealthStatus, DriveLetter, SizeRemaining, DriveType | Export-Csv -NoTypeInformation -Path C:\temp\software1.csv
Keep in mind you need to have the Import-Excel Module loaded but you should be able to use this to output to Excel.
#check-DiskSpace_FSs.ps1
import-module activedirectory
$dc = "domainController09"
$currentDate = get-date -Format yyyyMMdd_HHmm
$path = "\\UNC\export\FileServer_DiskSpace\FileServer_DiskSpace_$currentDate.xlsx"
$smtpServer = "10.10.10.10"
$from = "me#somewhere.com"
$to = "me#somewhere.com"
$subject = "Server FS diskspace - $date"
$ServerFSs = get-adcomputer -Server $dc -SearchBase "OU=fs,OU=Server,DC=somewhere,DC=com" -filter * | select name | sort Name
$DriveSize = foreach ($FS in $somewhereFSs)
{
get-WmiObject win32_logicaldisk -ComputerName $FS.name -Filter "Drivetype=3" | select SystemName,DeviceID,#{n="TotalSize(GB)";e={$_.Size / 1gb -as [int] }}`
,#{n="FreeSize(GB)";e={$_.freespace / 1gb -as [int] }}`
,#{n="FreeSize(%)";e={[int]($_.Freespace*100/$_.Size)}},VolumeName | Export-Excel -Path $path -append -FreezeTopRow -BoldTopRow -AutoSize -AutoFilter
}
Send-Mailmessage -smtpServer $smtpServer -from $from -to $to -subject $subject -Attachments $path -priority High

Export Powershell command to Excel

I have the following command
Get-WmiObject win32_OperatingSystem |%{"Total Physical Memory: {0}KB`nFree Physical Memory : {1}KB`nTotal Virtual Memory : {2}KB`nFree Virtual Memory : {3}KB" -f $_.totalvisiblememorysize, $_.freephysicalmemory, $_.totalvirtualmemorysize, $_.freevirtualmemory}
I want to export the above output to an excel file. I have:
Get-WmiObject win32_OperatingSystem |%{"Total Physical Memory: {0}KB`nFree Physical Memory : {1}KB`nTotal Virtual Memory : {2}KB`nFree Virtual Memory : {3}KB" -f $_.totalvisiblememorysize, $_.freephysicalmemory, $_.totalvirtualmemorysize, $_.freevirtualmemory} | Select-Object VisibleMem, FreeMem, VirtualMem,FreeVirtualMem | Export-Csv -Path "C:\Test.csv" -Encoding ascii -NoTypeInformation -UseCulture
This doesn't output anything besides titles of columns.I am looking for the output in each column. Any help?
You're throwing away the object with its properties when you create the the strings in your Foreach-Object loop so you don't have anything to export to csv anymore.
The property names in Select-Object doesn't exist. You can't make up column names (without using calculated properties/columns, see sample of this below).
Try this to output the data:
Get-WmiObject win32_OperatingSystem |
Select-Object TotalVisibleMemorySize, FreePhysicalMemory, TotalVirtualMemorySize, FreeVirtualMemory |
Export-Csv -Path "C:\Test.csv" -Encoding ascii -NoTypeInformation -UseCulture
If you need different column-names:
Get-WmiObject win32_OperatingSystem |
Select-Object #{n="VisibleMem";e={$_.TotalVisibleMemorySize}}, #{n="FreeMem";e={$_.FreePhysicalMemory}}, #{n="VirtualMem";e={$_.TotalVirtualMemorySize}}, #{n="FreeVirtualMem";e={$_.FreeVirtualMemory}} |
Export-Csv -Path "C:\Test.csv" -Encoding ascii -NoTypeInformation -UseCulture
If you need to write the text to the screen (for the user to see) while also saving them you would need to use Write-Host and remember to let the object passthrough to the next cmdlet in the pipeline:
Get-WmiObject win32_OperatingSystem |
ForEach-Object {
#Write to screen
Write-Host ("Total Physical Memory: {0}KB`nFree Physical Memory : {1}KB`nTotal Virtual Memory : {2}KB`nFree Virtual Memory : {3}KB" -f $_.totalvisiblememorysize, $_.freephysicalmemory, $_.totalvirtualmemorysize, $_.freevirtualmemory);
#Throw the original object to the next cmdlet in the pipeline
$_
} |
Select-Object TotalVisibleMemorySize, FreePhysicalMemory, TotalVirtualMemorySize, FreeVirtualMemory |
Export-Csv -Path "C:\Test.csv" -Encoding ascii -NoTypeInformation -UseCulture

Output Value from select-object calculated value

I've used a hash table to calculate some values for my VMWare inventory script, but now when I output the data, it records it as a key/value pair. I'd like to dump just the value. When I simply take what I'm handed that works fine, but when I get picky PS starts to stonewall me. :-)
Here is the relevant part of the script.
foreach ($machine in $vmList) {
$vmname = $machine.Name
$properties = #{
'Name'=Get-VM $vmname | Select -ExpandProperty Name
'RAM'=Get-VM $vmname | Select -ExpandProperty MemoryGB
'CpuCount'=Get-VM $vmname | Select -ExpandProperty NumCpu
'UsedDiskGB'=Get-VM $vmname | Select-Object #{n="UsedDiskGB"; e={[math]::Round( $_.UsedSpaceGB, 3 )}}
'TotalDiskGB'=Get-VM $vmname | Select-Object #{n="TotalDiskGB"; e={[math]::Round((Get-HardDisk -vm $_ | Measure-Object -Sum CapacityGB).Sum)}}
'Networks'=Get-VM $vmname | Select-Object #{n="Networks"; e={(Get-NetworkAdapter -VM $_ |Sort-Object NetworkName |Select -Unique -Expand NetworkName) -join '; '}}
'OS'=(Get-VM -Name $vmname | Get-View).summary.config.guestFullName
}
$object=New-Object -TypeName PSObject -Prop $properties
Export-Csv -Path $WorkDir\vms.csv -Append -Encoding UTF8 -InputObject $Object
Write-Output $Object
}
How do I get UsedDiskGB, Networks and TotalDiskGB to display just the value instead of something like '#{TotalDiskGB=80}'? Ram, OS, CpuCount and Name work exactly as desired already.
Also, suggestions on doing this in a faster way are welcome. I'm sure all these calls can be done better. I had it done in a single line, but then they asked for OS to be added and that changed everything.
Easy, but bad way:
In the expression pipe to |Select -ExpandProperty <property name> to get just the value. Such as:
'TotalDiskGB'=Get-VM $vmname | Select-Object #{n="TotalDiskGB"; e={[math]::Round((Get-HardDisk -vm $_ | Measure-Object -Sum CapacityGB).Sum)}}|select -expand totaldiskgb
The better way:
Structure your properties better to start with. Try this:
'TotalDiskGB'= [math]::Round((Get-HardDisk -vm (Get-VM $vmname) | Measure-Object -Sum CapacityGB).Sum)
The reason you're having issues is because you are creating a PSCustomObject with your Select, and Totaldiskgb is a property of that object. You don't want to make an object, you just want the value of that property.
Edit: Thank you to #briantist for pointing out that Get-VM $vmname should be called once, and stored as an object to be used later, rather than called for each time it is needed for a member of $Properties. For example:
foreach ($machine in $vmList) {
$vmname = $machine.Name
$vmobject = Get-VM $vmname
$properties = #{
'Name'=$vmobject | Select -ExpandProperty Name
'RAM'=$vmobject | Select -ExpandProperty MemoryGB
'CpuCount'=$vmobject | Select -ExpandProperty NumCpu
'UsedDiskGB'=[math]::Round( $vmobject.UsedSpaceGB, 3 )
'TotalDiskGB'=[math]::Round((Get-HardDisk -vm $vmobject | Measure-Object -Sum CapacityGB).Sum)
'Networks'=(Get-NetworkAdapter -VM $vmobject |Sort-Object NetworkName |Select -Unique -Expand NetworkName) -join '; '
'OS'=($vmobject | Get-View).summary.config.guestFullName
}
$object=New-Object -TypeName PSObject -Prop $properties
Export-Csv -Path $WorkDir\vms.csv -Append -Encoding UTF8 -InputObject $Object
Write-Output $Object
}

Powershell: tablet output to string of lines with one space

$allSoftwareObj = Get-WmiObject -Class Win32_Product | Select-Object -Property Name, Version | ft -HideTableHeaders | ft -Wrap -AutoSize -Property Name, Version
$allSoftware = Out-String -InputObject $allSoftwareObj
echo $allSoftware
When I output this, I get a table structure. I don't want that.
How to get a new line per new output with only space between the Name and Version?
Wrong output now:
Microsoft SQL Server System CLR Types 10.51.2500.0
SQL Server 2012 Client Tools 11.1.3000.0
Wanted output:
Microsoft SQL Server System CLR Types 10.51.2500.0
Or:
Microsoft SQL Server System CLR Types (10.51.2500.0)
Try replacing the whole line with this:
Get-WmiObject -Class Win32_Product | % {"$($_.Name) ($($_.Version))"}
$allSoftwareObj = Get-WmiObject -Class Win32_Product | %{ $_.Name + " " + $_.Version}
$allSoftwareObj
You can do it like this:
Get-WmiObject -Class Win32_Product | Select-Object -Property Name, Version | % { write-host "$($_.name) ($($_.version))" }

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