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

通过循环连接三台服务器获取磁盘空间并转格式后发邮件

Solution: Simplified PowerShell Script for Disk Space Reporting with Email

Here's a practical, streamlined script that checks your servers' D drive space, converts raw byte values to intuitive units (TB/GB/MB), and sends the formatted results via email—all without repeating commands for each server.

Step 1: Helper Function for Readable Size Conversion

First, create a reusable function to turn those hard-to-read byte values into something human-friendly:

function Convert-ToReadableSize {
    param([decimal]$Bytes)
    
    # Define size units from smallest to largest
    $sizeUnits = @('B', 'KB', 'MB', 'GB', 'TB')
    $unitIndex = 0
    
    # Divide by 1024 until we reach a manageable unit
    while ($Bytes -ge 1024 -and $unitIndex -lt $sizeUnits.Count - 1) {
        $Bytes /= 1024
        $unitIndex++
    }
    
    # Return formatted string with 2 decimal places for clarity
    return "{0:N2}{1}" -f $Bytes, $sizeUnits[$unitIndex]
}

Step 2: Main Script Logic

This section uses a loop to iterate over your server list, collects disk data, and processes it with the helper function. It also includes error handling for unreachable servers or permission issues:

# List of servers to check (easily add/remove entries here)
$targetServers = @('server01', 'server02', 'server03')

# Collect and process disk space data
$diskReport = foreach ($server in $targetServers) {
    try {
        # Fetch D drive info from the remote server
        $driveData = Invoke-Command -ComputerName $server -ScriptBlock { Get-PSDrive D } -ErrorAction Stop
        
        # Create a clean object with formatted values
        [PSCustomObject]@{
            'Server Name' = $server
            'Used Space'  = Convert-ToReadableSize $driveData.Used
            'Free Space'  = Convert-ToReadableSize $driveData.Free
        }
    }
    catch {
        # Handle errors gracefully and report them in the output
        [PSCustomObject]@{
            'Server Name' = $server
            'Used Space'  = "Error: $($_.Exception.Message.Split('`n')[0])"
            'Free Space'  = "Error: $($_.Exception.Message.Split('`n')[0])"
        }
    }
}

Step 3: Send Results via Email

Convert the report to a styled HTML table for clean email formatting, then send it using your SMTP server:

# Convert the report to a styled HTML table
$emailBody = $diskReport | ConvertTo-Html -Title "D Drive Space Report" -Head @"
<style>
    table {border-collapse: collapse; width: 80%; margin: 20px auto;}
    th, td {border: 1px solid #ddd; padding: 10px; text-align: left;}
    th {background-color: #f2f2f2; font-weight: bold;}
    body {font-family: Arial, sans-serif;}
</style>
"@ | Out-String

# Configure email settings
$emailParams = @{
    From       = "disk-report@yourdomain.com"
    To         = "admin@yourdomain.com"
    Subject    = "D Drive Space Report - $(Get-Date -Format 'yyyy-MM-dd')"
    Body       = $emailBody
    BodyAsHtml = $true
    SmtpServer = "smtp.yourdomain.com"
    # Uncomment below if your SMTP server requires authentication
    # Credential = Get-Credential
}

# Send the email
Send-MailMessage @emailParams

Key Benefits

  • Loop-based execution: No redundant code—just update the $targetServers list to adjust which servers are checked.
  • Error resilience: Catches issues like offline servers or permission errors and reports them clearly in the final output.
  • Intuitive formatting: Converts raw bytes to TB/GB/MB with 2 decimal places for quick interpretation (e.g., 2.53T instead of 2534760280064).
  • Professional email output: Styled HTML ensures the report is easy to read in any email client.

Example Email Output

Server NameUsed SpaceFree Space
server012.53T238.90G
server022.53T18.63G
server032.53T1.82T

内容的提问来源于stack exchange,提问作者ursa Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:04:01