Export Powershell command to Excel - 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

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 CSV Writes Results to Single Line, How Do I get Multiple Lines?

I am looking for duplicates on a share drive so I can let the users know and they can clean it up before we use anything automated. My largest duplicate is close to 400 copies, but the info is all on a single line.
My query is getting the correct results:
$a = Get-ChildItem -Path "S:\" -File -Recurse |
Select-Object -Property Fullname, #{N='Hash';E={(Get-FileHash $_.FullName).Hash}}
$cnt = $a | Group-Object -Property Hash
$cnt |
Select-Object Count, #{N='FullName';E={($_.Group).FullName}}, #{N='Hash';E={($_.Group).Hash}} |
Sort-Object -Property Count -Descending |
Export-Csv C:\Temp\S_Drive_Counts.csv
Here is an example of my results where each entry is on a single line:
"Count","FullName","Hash"
"2","S:\Generation 1\Certification Authority.txt S:\Generation 2\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83 498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"
I need to pass this info on though, so I'd like to have each entry on a line by itself, similar to this:
"Count","FullName","Hash"
"2","S:\Generation 1\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"
"2","S:\Generation 2\Certification Authority.txt","498868376A5377F731593E9F96EC99F34C69F47537C81B9B32DBAC9321462B83"
I can do some string manipulation to the CSV if needed, but I am looking for a way to get it in the correct format before exporting to the CSV.
Unroll your groups. Also, make better use of the pipeline.
Get-ChildItem -Path 'S:\' -File -Recurse |
Select-Object Fullname, #{n='Hash';e={(Get-FileHash $_.FullName).Hash}} |
Group-Object Hash |
ForEach-Object {
$cnt = $_.Count
$_.Group | Select-Object #{n='Count';e={$cnt}}, FullName, Hash
} |
Sort-Object Count, Hash, FullName -Descending |
Export-Csv 'C:\Temp\S_Drive_Counts.csv' -NoType

Issue with export-csv no data?

In my report when I remove the export-csv portion the data is presented correctly onscreen, when I add in the export-csv no data is exported but the file is created. Below is my script along with what the data looks like when script is running (modified) of what the data looks like.
#Get all DHCP Servers
$ServerList = (Get-Content -Path "\\termserv\DHCPServers.txt")
foreach ($server in $serverlist)
{
#Get the scopes from each serve
Get-DHCPServerv4Scope -ComputerName $server | select ScopeID |
#Get the lease information for each scope
ForEach-Object {Get-DHCPServerv4Lease -ScopeId $_.ScopeId -ComputerName
$server -AllLeases |
where {$_.AddressState -like "*Reservation"} | Select-Object
$server,ScopeId,IPAddress,HostName,ClientID,AddressState | Export-
Csv "\\termserv\d$\term\User\Reservations1.csv"
}
}
What the data looks like when exported without export-csv
NOPEDH01 :
ScopeId : 000.11.2.3
IPAddress : 111.22.3.444
HostName : NOPE00112233
ClientID : 00-11-22-33-44-55
AddressState : ActiveReservation
NOPEDH01 :
ScopeId : 000.11.2.3
IPAddress : 111.22.3.445
HostName : NOPE0011223344
ClientID : 00-11-22-33-44-56
AddressState : ActiveReservation
Update: Tried that and still nothing, when I run a modified version of the script locally on my DH servers it functions correctly, but I'm looking at almost 100 DH servers in my environment, see below
Get-DHCPServerV4Scope | ForEach {
Get-DHCPServerv4Lease -ScopeID $_.ScopeID -AllLeases | where
{$_.AddressState -like '*Reservation'}
} | Select-Object ScopeId,IPAddress,HostName,ClientID,AddressState | Export-
Csv "\\termserv\d$\term\$($env:COMPUTERNAME)-Reservations1.csv" -
NoTypeInformation
This is a representation of what you are doing:
Foreach ($Server in $ServerList)
{
Foreach ($Scope in $ScopeList)
{
$Data | Export-csv -Path FileName.csv
}
}
In doing so you are exporting data [(Total Servers) x (Total Scopes per server)] times which is a lot of I/O operations. It is just a logistics issue. You could collect the entire information into a table object before exporting. But that decision is up to you and your particular business needs.
The real issue, however, is that you are doing the export into the same file which essentially over writes whatever you have written before without telling it not to. So only the last export remains which I suspect is somehow blank.
Try using the -Append switch when you export.
$Data | Export-csv -Path FileName.csv -NoTypeInformation -Append
Also I noticed you are using $server variable in the select-object cmdlet where you should only be using the object's property names and not variable names. I do not know if that returns anything as the cmdlet would not know what to do with it, which could also be contributing to the problem.
According to your code you are using Export-Csv within a foreach-object. Generally Export-csv creates a csv file with new data. If data is already present in the csv file then it will overwrite the existing data with new one.
So instead of using
Export-Csv "\\termserv\d$\term\User\Reservations1.csv"
You cand use
Export-Csv "\\termserv\d$\term\User\Reservations1.csv" -Force -Append -NoTypeInformation
Here -Append will append the data in the csv file. Not overwrites.

Passing PowerShell Output to CSV/Excel

I previously had asked a question regarding adding together files and folders with a common name and having them summed up with a total size (Sum of file folder size based on file/folder name). This was successfully answered with the PS script below:
$root = 'C:\DBFolder'
Get-ChildItem "$root\*.mdf" | Select-Object -Expand BaseName |
ForEach-Object {
New-Object -Type PSObject -Property #{
Database = $_
Size = (Get-ChildItem "$root\$_*\*" -Recurse |
Measure-Object Length -Sum |
Select-Object -Expand Sum ) / 1GB
}
}
This now leaves me with a list that is ordered by the 'Database' Property by default. I have attempted to use a Sort-Object suffix to use the 'Size' property with no joy. I have also attempted to use Export-Csv with confounding results.
Ideally, if I could pass the results of this script to Excel/CSV so I can rinse/repeat across multiple SQL Servers and collate the data and sort within Excel, I would be laughing all the way to the small dark corner of the office where I can sleep.
Just for clarity, the output is looking along the lines of this:
Database Size
-------- ----
DBName1 2.5876876
DBName2 4.7657657
DBName3 3.5676578
Ok, it was one pipe character that I had missed when using the Export-csv function. This resolved my problem.
$root = 'C:\DB\Databases'
Get-ChildItem "$root\*.mdf" | Select-Object -Expand BaseName |
ForEach-Object {
New-Object -Type PSObject -Property #{
Database = $_
Size = (Get-ChildItem "$root\$_*\*" -Recurse |
Measure-Object Length -Sum |
Select-Object -Expand Sum ) / 1GB
}
} | Export-Csv 'C:\Test\test.csv'

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

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.

Resources