gpt4 book ai didi

powershell - 在 PowerShell 中创建带有变量的表

转载 作者:行者123 更新时间:2023-12-04 17:00:38 27 4
gpt4 key购买 nike

我仍在学习 PowerShell 脚本,我正在编写一个脚本来计算文件服务器的可用空间百分比,并在驱动器剩余可用空间的 10% 或更少时发送电子邮件通知(这种情况会发生大约每月一次,我需要在收到客户的电子邮件之前知道没有更多空间)。截至目前,该脚本运行良好,并设置为每天早上通过 Windows 任务运行。但是我为输出设置的当前格式是手动完成的。我想知道是否有办法从使用 Get-WmiObject 函数收集和计算的信息中传递变量。我试过 Format-Table 并尝试弄乱哈希表,但无济于事。任何想法都会有所帮助。谢谢。

# Set Parameters
$file = "c:\location\Lowdisk.txt"
Clear-Content $file

$emailTO = "Someone@SomeDomain.com"
$emailFrom = "Someone@SomeDomain.com"
$smtpServer = "smtpServer"

$diskspace = "3"
$computers = ("FSCN01","FSCN02","FSCN03","FSCN04")
echo "Server Name Drive Drive Size Free Space % Free" >> $file
$i = 0

# Get Drive Data
foreach($computer in $computers)
{
$drives = Get-WmiObject -ComputerName $computer Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3}
foreach($drive in $drives)
{
$ID = $drive.DeviceID
$size1 = $drive.size / 1GB
$size = "{0:N1}" -f $size1
$free1 = $drive.freespace / 1GB
$free = "{0:N1}" -f $free1
$a = $free1 / $size1 * 100
$b = "{0:N1}" -f $a
# Monitor for drive free space % under 10%
if ($b -lt 10)
{
echo "$computer $ID $size $free $b" >> $file
$i++
}
}
}
# Send notification if script finds more than 0 drives with less than 35% 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 Get-Content $file)
{
$body += "$line `n"
}
Send-MailMessage -to $user -From $emailFrom -Attachments $file -SmtpServer $smtpServer -Subject $Subject -Body $body
$body = ""
}
}

最佳答案

Format-Table当您在单一类型的对象中拥有所有感兴趣的数据时,效果最佳。我建议为此创建自定义对象,例如:

foreach($computer in $computers)
{
$drives = Get-WmiObject -ComputerName $computer Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3}
foreach($drive in $drives)
{
$obj = new-object psobject -Property @{
ComputerName = $computer
Drive = $drive.DeviceID
Size = $drive.size / 1GB
Free = $drive.freespace / 1GB
PercentFree = $drive.freespace / $drive.size * 100
}
if ($obj.PercentFree -lt 10) {
$obj | Format-Table ComputerName,Drive,Size,Free,PercentFree
$i++
}
}
}

如果要更改显示格式,则可以在 format-table 命令中执行以下操作:
$obj | Format-Table ComputerName,Drive,@{n='Size';e={'{0:N1}' -f $_.Size}},Free,PercentFree

关于powershell - 在 PowerShell 中创建带有变量的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21838419/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com