cdchenli 发表于 2018-9-1 12:18:01

Powershell Excel Module

  参考文档:
  https://blogs.technet.microsoft.com/heyscriptingguy/2015/11/25/introducing-the-powershell-excel-module-2/
  https://github.com/dfinke/ImportExcel
  把Powershell中的数据导出来并能很容易的加工好像一直是一个问题,比如说,导出成CSV格式。
  普及一个知识,CVS Comma-Seperated Value 文件。呵呵,我也是刚知道的,以前还纳闷呢。
  举个例子,我们以前的做法就是:
  Get-Process | Export-Csv c:\Temp\ps.csv #生成CSV文件
  Invoke-Item c:\temp\ps.csv#打开看看
  还有一种方法,前提就是那台电脑得安装了EXCEL程序,利用EXCEL COM组件来打开的。如下所示:
  $xl = New-Object -ComObject excel.application   #生成一个EXCEL类的实例
  $xl.visible = $true#让这个实例显示出来
  $xl.workbooks.add() #添加一个默认的表格
  好消息就是现在有一个EXCEL模块来支持了,如果你的电脑的Powershell版本是5.0 可以用以下命令直接安装这个模块,然后就可以直接调用啦,非常强大的功能。
  PS C:\> Install-Module importexcel
  Untrusted repository
  You are installing the modules from an untrusted repository. If you trust this repository, change its InstallationPolicy
  value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from 'PSGallery'?
   Yes Yes to All No No to All Suspend[?] Help (default is "N"): y
  安装成功后,非常惊喜的发现:
  Get-Process | Export-Excel c:\temp\psnew.xlsx -show
  当然这只是一个开始,更强大的功能还在后面呢。打开一个ISE,把下面的代码放进去,运行看一下结果:
rm $file -ErrorAction Ignore  

  
ps |
  
    where company |
  
    select Company,PagedMemorySize,PeakPagedMemorySize |
  
    Export-Excel $file -Show -AutoSize `
  
      -IncludePivotTable `
  
      -IncludePivotChart `
  
      -ChartType ColumnClustered `
  
      -PivotRows Company `
  
      -PivotData @{PagedMemorySize='sum';PeakPagedMemorySize='sum'}

  当然,还有一些更不可思议的执行效果:
$ps = ps  

  
$ps |
  
    Export-Excel .\testExport1.xlsx-WorkSheetname memory `
  
      -IncludePivotTable -PivotRows Company -PivotData PM `
  
      -IncludePivotChart -ChartType PieExploded3D
  
$ps |
  
    Export-Excel .\testExport1.xlsx-WorkSheetname handles `
  
      -IncludePivotTable -PivotRows Company -PivotData Handles `
  
      -IncludePivotChart -ChartType PieExploded3D -Show




页: [1]
查看完整版本: Powershell Excel Module