简体   繁体   中英

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?

  1. 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.
  2. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM