快速将字节转换为兆字节

时间:2019-10-28 16:47:30

标签: powershell

在下面的PS命令中,我在gcp项目中获取了昨天快照的名称,creationTimeStamp,Disk_Size和storageBytes,并将数据输出到一个csv文件(该文件随后转换为HTML并通过电子邮件发送):

$csv = gcloud --project $gcpProject compute snapshots list --format="csv(name,creationTimestamp,diskSizeGb,storageBytes)" --filter="creationTimestamp.date('%Y-%m-%d')=$yesterday" | Out-File C:\data.csv

结果看起来像这样(显示的快照数量有所不同):

+---------------------------+-------------------------------+--------------+---------------+
|               NAME        |       CREATION_TIMESTAMP      | DISK_SIZE_GB | STORAGE_BYTES |
+---------------------------+-------------------------------+--------------+---------------+
| snapshot1-us-central1     | 2019-10-24T19:24:09.061-07:00 | 50           | 1250586048    |
| snapshot2-data-us-east1   | 2019-10-24T19:01:49.791-07:00 | 150          | 425018600     |
+---------------------------+-------------------------------+--------------+---------------+

这很好,除了STORAGE_BYTES数据全部以字节为单位,因此很难读取。如何在MB中而不是在csv文件中记录此数据(或仅将MB中以字节为单位的csv文件中的数据替换)

2 个答案:

答案 0 :(得分:1)

$data=Get-Content C:\data.csv
$NewData=@($data[0..2])#Adding Header in a new Variable
$Data[3..$($data.Count - 2)]|Foreach{
$startRange=$_.LastIndexOf("| ")+1
$length=$_.LastIndexOf("  |") - $_.LastIndexOf("| ")
#Converting Bytes into MB and replacing in the line
$NewData+=$_.Replace(($_.Substring($startRange,$length)).Trim(),"$([math]::Round(($_.Substring($startRange,$length)/1MB),2))   ")
}
#Adding last line
$NewData+=$data[$data.Count - 1]
#Modifying exsiting file
$NewData |Set-Content C:\data.csv -Force

答案 1 :(得分:0)

我认为,使用GCP PowerShell cmdlet应该很简单。

Get-GceSnapshot -Project $gcpProject

我从未使用过它,但是您可以使用计算出的属性将尺寸转换为一行,例如下面的示例

Get-Process | Select-Object -First 3 -Property Name,@{E={$_.STORAGE_BYTES/1024};L='Size'}

PS:假设大小属性名称为 STORAGE_BYTES

https://googlecloudplatform.github.io/google-cloud-powershell/#/google-compute-engine/GceSnapshot/Get-GceSnapshot