You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell编写脚本获取Active Directory域内计算机磁盘空间信息

获取AD域内所有计算机磁盘空间信息的PowerShell脚本

Hey there, since you already have a solid PowerShell base, putting together this disk space script should be straightforward—let's break it down into something reliable that handles common headaches like offline machines or permission issues.

Prerequisites First

Before diving in, make sure you have these covered:

  • The RSAT-AD-PowerShell module installed. On modern Windows, you can grab it via:
    Install-WindowsFeature RSAT-AD-PowerShell
    
    Or through Windows Settings > Apps > Optional features > Add a feature > search for "Active Directory Module for Windows PowerShell".
  • Your account needs read access to Active Directory, plus WMI/CIM permissions on the target domain computers to pull disk data.

The Script

Here's a complete, commented script that does the job:

# Import the AD module (fail fast if it's missing)
Import-Module ActiveDirectory -ErrorAction Stop

# Get all domain computers (filter out disabled ones if needed)
$domainComputers = Get-ADComputer -Filter * -Properties Name, DNSHostName

# Initialize an array to store results
$diskSpaceResults = @()

# Loop through each computer
foreach ($computer in $domainComputers) {
    $computerName = $computer.DNSHostName ? $computer.DNSHostName : $computer.Name
    Write-Host "Checking disk space on $computerName..."

    try {
        # Use CIM (more modern than WMI) to get disk info
        $diskInfo = Get-CimInstance -ClassName Win32_LogicalDisk -ComputerName $computerName `
            -Filter "DriveType=3" -ErrorAction Stop
        
        # Process each disk drive
        foreach ($disk in $diskInfo) {
            # Calculate used space and percentages
            $usedSpaceGB = [math]::Round(($disk.Size - $disk.FreeSpace) / 1GB, 2)
            $freeSpaceGB = [math]::Round($disk.FreeSpace / 1GB, 2)
            $usedPercent = [math]::Round((($disk.Size - $disk.FreeSpace) / $disk.Size) * 100, 2)

            # Add to results array
            $diskSpaceResults += [PSCustomObject]@{
                ComputerName   = $computerName
                DriveLetter    = $disk.DeviceID
                TotalSizeGB    = [math]::Round($disk.Size / 1GB, 2)
                UsedSpaceGB    = $usedSpaceGB
                FreeSpaceGB    = $freeSpaceGB
                UsedPercentage = "$usedPercent%"
            }
        }
    }
    catch {
        # Log errors for offline/access-denied machines
        $diskSpaceResults += [PSCustomObject]@{
            ComputerName   = $computerName
            DriveLetter    = "N/A"
            TotalSizeGB    = "N/A"
            UsedSpaceGB    = "N/A"
            FreeSpaceGB    = "N/A"
            UsedPercentage = "Error: $($_.Exception.Message)"
        }
        Write-Warning "Failed to retrieve data from $computerName : $($_.Exception.Message)"
    }
}

# Output results to console and export to CSV (optional but useful)
$diskSpaceResults | Format-Table -AutoSize
$diskSpaceResults | Export-Csv -Path "DomainDiskSpaceReport.csv" -NoTypeInformation -Encoding UTF8

Write-Host "Report generated successfully! Check DomainDiskSpaceReport.csv for full details."

Key Notes & Customizations

  • Filtering computers: If you don't want to check every computer, adjust the Get-ADComputer filter. For example, -Filter "Enabled -eq $true" to skip disabled machines, or -SearchBase "OU=Servers,DC=contoso,DC=com" to target a specific OU.
  • Drive type: The DriveType=3 filter targets fixed hard drives. Adjust this if you want to include removable drives (DriveType=2) or others.
  • Error handling: The script catches and logs errors, so you'll know exactly which machines you couldn't reach.
  • Output: The CSV export makes it easy to analyze in Excel or other tools—just tweak the file path as needed.

Running the Script

Save it as Get-DomainDiskSpace.ps1, then run it in an elevated PowerShell window (right-click > Run as Administrator) to avoid permission issues.

内容的提问来源于stack exchange,提问作者Carl O'Beirne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:20:14