通过循环连接三台服务器获取磁盘空间并转格式后发邮件
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
$targetServerslist 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.53Tinstead of2534760280064). - Professional email output: Styled HTML ensures the report is easy to read in any email client.
Example Email Output
| Server Name | Used Space | Free Space |
|---|---|---|
| server01 | 2.53T | 238.90G |
| server02 | 2.53T | 18.63G |
| server03 | 2.53T | 1.82T |
内容的提问来源于stack exchange,提问作者ursa Brown
相关产品推荐
相关产品推荐

