收集磁盘分区信息(总量、可用、已用、百分比)导出到csv

时间:2021-10-12 14:10:35

#############################脚本功能及说明#################################################
#该脚本用来收集磁盘分区总大小、可用空间、已用空间、已用空间百分比,输出到csv
############################################################################################

$file_server = "Serverlist.txt"
$result = "DiskInfor.csv"
$CurrentPath = $MyInvocation.MyCommand.Path.substring(0,$MyInvocation.MyCommand.Path.LastIndexOf('\')+1)
$server_list = $CurrentPath + $file_server
$diskPath = $currentpath + $result
$servers = Get-Content $server_list
$UserName = "administrator"
#$UserName = "erpadmin"
$ics=$null
Foreach ($server in $servers)
{
$servername = $server.split(",")[0]
$serverpass = $server.split(",")[1]
#net use \\$servername $serverpass /user:$UserName |out-null
$Password = ConvertTo-SecureString $serverpass -AsPlainText –Force
$cred = New-Object System.Management.Automation.PSCredential($UserName,$Password)
Write-Host $servername -ForegroundColor Green

$ic = invoke-command -ComputerName $servername -Credential $cred -ScriptBlock {param($servername)
function disksize ($servername)
{
$disks = Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -computer $servername
$results=@()
foreach ($disk in $disks)
{
$deviceid = $disk.deviceid
$size = ($disk.size/1024/1024/1024).tostring("f1")
$free = ($disk.freespace/1024/1024/1024).tostring("f1")
$used = $size-$free
$perc = "{0:p}" -f($disk.freespace/$disk.size)
$result=""|select name,idd,size,free,used,perc
$result.name = $servername
$result.idd = $deviceid
$result.size = $size
$result.free = $free
$result.used = $used
$result.perc = $perc
$results += $result
}
$results
}
disksize $servername
} -ArgumentList $servername
$ics += $ic
$ics|select name,idd,size,free,used,perc |Export-Csv $diskPath -NoTypeInformation
}
#$results |Export-Csv $memPath -NoTypeInformation
#net use * /del /y |out-null
#cmd /c pause