簡體   English   中英

如何使用Powershell在Windows Server中以csv格式獲取磁盤詳細信息

[英]How can i get the disk details in csv format in windows server using powershell

大家好,我想獲取以下格式的詳細信息

Hostname    Drive_0              Drive_1             Drive_2

Name        C: 99.899227142334   d: 99.899227142334  e: 99.899227142334

我可以使用下面的腳本獲取此詳細信息,但這可以在PowerShell 3.0上運行,如何更改為在PowerShell 2.0上執行

$result = @()
$obj = new-object PSobject
$server = hostname
$obj |Add-Member -MemberType NoteProperty -Name "Hostname" -Value $server -ErrorAction SilentlyContinue
$z = Get-WmiObject -Class win32_Logicaldisk -Filter 'DriveType=3' | Select-Object -Property DeviceID,  @{LABEL='TotalSize';EXPRESSION={$_.Size/1GB}}

$z3 = $z.DeviceID
$z4 = $z.TotalSize
$i = 0
foreach($z3 in $z3){
 $z1 = $z.DeviceID[$i]
 $z2 = $z.TotalSize[$i]
    $zx = "$z1" + ": $z2"

      $obj | Add-Member -MemberType NoteProperty -Name "Drive_$i" -Value $zx -ErrorAction SilentlyContinue

$i++
  }
   $result+=$obj
     $result | Export-Csv  "$env:userprofile\Desktop\Result.csv" -NoTypeInformation

您可以將代碼更改為以下內容。 有點整潔,整理出循環和限制,因此您無需管理它們

$result = @()
$obj = new-object PSobject
$server = hostname
$obj |Add-Member -MemberType NoteProperty -Name "Hostname" -Value $server -ErrorAction SilentlyContinue
$z = Get-WmiObject -Class win32_Logicaldisk -Filter 'DriveType=3' | Select-Object -Property DeviceID,  @{LABEL='TotalSize';EXPRESSION={$_.Size/1GB}}

$i = 0
$z | % {
  $z1 = $_.DeviceID
  $z2 = $_.TotalSize
  $zx = "$z1" + ": $z2"
  $obj | Add-Member -MemberType NoteProperty -Name "Drive_$i" -Value $zx 
  $i++
}
$result+=$obj
$result | Export-Csv  "$env:userprofile\Desktop\Result.csv" -NoTypeInformation

我還刪除了Add-Member-ErrorAction ,因為您應該嘗試處理任何會引起-ErrorAction的問題,但是如果需要,可以重新添加。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM