【发布时间】:2016-11-18 16:15:11
【问题描述】:
我无法获得正确的 PowerShell 输出。
输出示例如下:
计算机名 |驱动器 |尺寸 |免费 |百分比免费
COMP-NAME H:249 11 4.5计算机名 |驱动器 |尺寸 |免费 |百分比免费
COMP-NAME C:67 3.2 4.7计算机名 |驱动器 |尺寸 |免费 |百分比免费
COMP-NAME H:249 11 4.5计算机名 |驱动器 |尺寸 |免费 |百分比免费
COMP-NAME C:67 3.2 4.7计算机名 |驱动器 |尺寸 |免费 |百分比免费
COMP-NAME H:249 11 4.5计算机名 |驱动器 |尺寸 |免费 |百分比免费
COMP-NAME C:67 3.2 4.7计算机名 |驱动器 |尺寸 |免费 |百分比免费
COMP-NAME H:249 11 4.5计算机名 |驱动器 |尺寸 |免费 |百分比免费
COMP-NAME C:67 3.2 4.7
下面的脚本查询主机是否存在低于特定阈值的低磁盘并将其发送到相应的电子邮件。脚本运行良好,但我不断收到重复的行。
有人可以帮忙吗?谢谢。
#THE SCRIPT
# Set Global Parameters
$emailTO = "email@email.com"
$emailFrom = "LowSpaceNotify@email.com"
$smtpServer = "X.X.X.X"
$computers = "COMP-NAME"
$i = 0
# Get Drive Data
$report = @(
foreach($computer in $computers)
{
$drives = Get-WmiObject -ComputerName $computer Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3}
foreach($drive in $drives)
{
# Calculate Free Space
$obj = new-object psobject -Property @{
ComputerName = $computer
Drive = $drive.DeviceID
Size = $drive.size / 1GB
Free = $drive.freespace / 1GB
PercentFree = $drive.freespace / $drive.size * 100
}
# Monitor for 10% or less in free space and report accordingly
if ($obj.PercentFree -lt 10) {
$obj | Format-Table ComputerName,Drive,@{n='Size';e={'{0:N1}' -f $_.Size}},@{n='Free';e={'{0:N1}' -f $_.Free}},@{n='PercentFree';e={'{0:N1}' -f $_.PercentFree}} | Out-String
$i++
}
}
}
)
# Send notification if script finds more than 0 drives with less than 10% free space
if ($i -gt 0)
{
foreach ($user in $emailTo)
{
echo "Sending Email Notification to $user"
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$subject = "Server with Low Disk Space"
foreach ($line in $report)
{
$body += "$line "
}
Send-MailMessage -to $user -From $emailFrom -SmtpServer $smtpServer -Subject $Subject -Body $body
}
}
【问题讨论】:
-
foreach ($line in $report)应该迭代什么?您没有将$report分配给任何东西。# Send notification...评论之前的右括号没有与任何内容配对。一个有效的 MCVE 将帮助您更快地获得答案。 -
看起来报告在脚本中被分配到foreach($computers in $computers)循环中的所有输出的较高位置,这有点奇怪,但应该可以正常工作。不知道你所说的“重复行”是什么意思你能举一个你目前得到的输出的例子吗?
-
嗨,Tony,正如 Mike 所说,$report 已分配。
-
Mike,在脚本之前提供了重复的行。它们前面带有“输出示例如下:”语句。基本上,它应该是 2 行,但是这些行重复了 4 次,这对我来说似乎很奇怪。谢谢。
标签: powershell scripting