Powershell - 将磁盘空间结果导出为CSV

时间:2016-11-03 14:57:45

标签: powershell csv diskspace

我有以下代码,可以在服务器上找到名为' Automate'的驱动器上的可用空间。并将结果输出到.csv文件:

$AutomateD = @()

Clear-Host

$AutomateD += Get-WmiObject Win32_logicaldisk -ComputerName Automate ` | Where-Object {$_.VolumeName -ne 'Logs' -and $_.DeviceID -eq 'D:'}| Format-Table DeviceID, MediaType, `
@{Name="Size(GB)";Expression={[decimal]("{0:N0}" -f($_.size/1gb))}}, `
@{Name="Free Space(GB)";Expression={[decimal]("{0:N0}" -f($_.freespace/1gb))}}, `
@{Name="Free (%)";Expression={"{0,6:P0}" -f(($_.freespace/1gb) / ($_.size/1gb))}} `
-AutoSize

$AutomateD | Export-Csv -path "C:\Powershell\Automate\AutomateD.csv" -NoTypeInformation -Encoding Unicode
$ImportAutoD = Import-CSV C:\Powershell\Automate\AutomateD.csv | ConvertTo-Html

问题是当我打开csv -

时,我得到了一些奇怪的结果

" ClassId2e4f51ef21dd47e99d3c952918aff9cd"" pageHeaderEntry"" pageFooterEntry"" autosizeInfo"" shapeInfo"&# 34; groupingEntry" " 033ecb2bc07a4d43b5ef94ed5a35d280" ,,," Microsoft.PowerShell.Commands.Internal.Format.AutosizeInfo"" Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo&#34 ;, " 9e210fe47d09416682b841769c78b8a3" ,,,,, " 27c87ef9bbda4f709f6b4002fa4af63c" ,,,,, " 4ec4f0187cb04f4cb6973460dfe252df" ,,,,, " cf522b78d86c486691226b40aa69e95c" ,,,,,

但是,如果我只是在屏幕上输出$AutomateD变量,我会得到一个漂亮的表:

PS C:\Powershell\SCRIPT> $AutomateD

DeviceID MediaType Size(GB) Free Space(GB) Free (%)
-------- --------- -------- -------------- --------
D:              12     1225            183    15%

关于发生了什么的任何想法?在出口过程中似乎存在问题,尽管我没有任何错误可以继续我的错误。

2 个答案:

答案 0 :(得分:1)

You need to remove the format-table and replace it with a select-object. You'll also need to drop the -autosize from the end of your pipeline. In addition it is not required but I would recommend dropping the kind odd array creation and then adding a single value to the array, the script can actually get done in a single pipeline with the exception of the import-csv (which I'm not really sure you need but I'll leave it in assuming it's required elsewhere in the script)

Clear-Host

Get-WmiObject Win32_logicaldisk ` | Where-Object {$_.VolumeName -ne 'Logs' -and $_.DeviceID -eq 'D:'}| Select-Object DeviceID, MediaType, `
@{Name="Size(GB)";Expression={[decimal]("{0:N0}" -f($_.size/1gb))}}, `
@{Name="Free Space(GB)";Expression={[decimal]("{0:N0}" -f($_.freespace/1gb))}}, `
@{Name="Free (%)";Expression={"{0,6:P0}" -f(($_.freespace/1gb) / ($_.size/1gb))}} |
Export-Csv -path d:\scripts\test.csv -NoTypeInformation -Encoding Unicode -Force

$ImportAutoD = Import-CSV d:\scripts\test.csv | ConvertTo-Html

Also note that I did make some path changes to make it work on my machine without building out a new folder structure.

答案 1 :(得分:-1)

导出csv时使用-NoTypeInformation