Cドライブ以外もOK|複数手法・関数化・用途別に徹底解説
Windowsの運用やスクリプト作成をしていると、
と感じることは多いはずです。
本記事では
Windowsでドライブ容量を取得する代表的な方法をすべて整理し、
さらに「特定のドライブを指定して取得できる関数」まで解説します。
PowerShellでは、目的に応じて複数の取得ルートがあります。
① Get-PSDrive → ユーザー向け(簡単)
② Get-Volume → ドライブ(正確)
③ Get-Disk → 物理ディスク
④ Get-Partition → パーティション
重要なのは
**「どの階層の情報が欲しいか」**です。
Get-PSDrive -PSProvider FileSystem
Get-PSDrive C
Get-Volume
Get-Volume -DriveLetter C
(Get-Volume -DriveLetter C).Size
👉 ドライブ単位で容量を知りたいなら最も正確
Get-Disk | Get-Partition | Get-Volume
この方法は、
を正しく関連付けられる 運用・調査向けの王道ルートです。
(Get-Disk | Get-Partition | Get-Volume |
Where-Object DriveLetter -eq 'C').Size
function Get-CDriveSizeGB {
$v = Get-Disk | Get-Partition | Get-Volume |
Where-Object DriveLetter -eq 'C'
if (-not $v) {
throw "Cドライブが見つかりません"
}
[math]::Round($v.Size / 1GB, 2)
}
function Get-DriveSizeGB {
param (
[Parameter(Mandatory)]
[ValidatePattern('^[A-Z]$')]
[string]$DriveLetter
)
$volume = Get-Disk | Get-Partition | Get-Volume |
Where-Object { $_.DriveLetter -eq $DriveLetter }
if (-not $volume) {
throw "ドライブ $DriveLetter が見つかりません"
}
[math]::Round($volume.Size / 1GB, 2)
}
Get-DriveSizeGB -DriveLetter C
Get-DriveSizeGB -DriveLetter D
476.94
931.51
function Get-DriveInfo {
param (
[string]$DriveLetter
)
Get-Disk | Get-Partition | Get-Volume |
Where-Object DriveLetter -eq $DriveLetter |
Select-Object `
DriveLetter,
FileSystemLabel,
@{Name="SizeGB";Expression={[math]::Round($_.Size/1GB,2)}},
@{Name="FreeGB";Expression={[math]::Round($_.SizeRemaining/1GB,2)}}
}
| 用途 | おすすめ |
|---|---|
| さっと確認 | Get-PSDrive |
| 正確な容量 | Get-Volume |
| 構成調査 | Get-Disk + Get-Partition |
| スクリプト | 関数化(引数指定) |
| 監視 | オブジェクト返却 |
if (Get-DriveSizeGB -DriveLetter C -lt 100) {
Write-Warning "Cドライブ容量が100GB未満です"
}
Get-Disk → Get-Partition → Get-Volume は覚えておくべき王道ルート