서버의 여유 디스크 공간을 보고하는 PowerShell 스크립트

서버의 여유 디스크 공간을 보고하는 PowerShell 스크립트

Exchange 서버의 여유 디스크 공간에 대한 보고서를 받아야 합니다. 이 링크를 찾았습니다.https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Script-Sample-f7164554

하지만 성공적으로 실행할 수 없습니다. 누구든지 이 작업을 수행하는 더 좋고/쉬운 방법이 있습니까? 보고서는 이메일로 필요하지 않습니다...단지 csv 파일로요. 저는 Windows 10을 사용하고 있습니다. $PSVersionTable에 다음이 표시됩니다.

Name                           Value    
PSVersion                      5.1.14393.3053                                                                                                                                                 
PSEdition                      Desktop                                                                                                                                                        
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                                                        
BuildVersion                   10.0.14393.3053                                                                                                                                                
CLRVersion                     4.0.30319.42000                                                                                                                                                
WSManStackVersion              3.0                                                                                                                                                            
PSRemotingProtocolVersion      2.3                                                                                                                                                            
SerializationVersion           1.1.0.1

내가 얻는 오류 :

-ErrorAction : The term '-ErrorAction' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, 
verify that the path is correct and try again.
At C:\scripts\getdiskspace.ps1:7 char:1
+ -ErrorAction SilentlyContinue
+ ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (-ErrorAction:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

-ComputerName과 동일하지만 이상한 점은 여전히 ​​실행되고 csv 파일을 생성하지만 4개의 ​​서버 대신 로컬 호스트의 디스크 크기 목록만 있다는 것입니다.

이 스크립트가 이메일을 보내도록 할 수 있었고 작업 스케줄러를 사용하여 매주 실행할 수 있었습니다. 이 오류를 파악하고 서버(locolhost) 디스크 크기가 하나만 표시되는 이유를 알아내면 됩니다. 내가 사용한 정확한 스크립트는 다음과 같습니다.

$File = Import-csv C:\scripts\getdiskspace.csv
$DiskReport = ForEach ($Servernames in ($File))  
 
{
Get-WmiObject win32_logicaldisk <#-Credential $RunAccount#> ` 
-ComputerName $Servernames -Filter "Drivetype=3" ` 
-ErrorAction SilentlyContinue 
 
#return only disks with 
#free space less   
#than or equal to 0.1 (10%) 
 
#Where-Object {   ($_.freespace/$_.size) -le '0.1'} 
 
}  
 
 
#create reports 
 
$DiskReport |  
 
Select-Object @{Label = "Server Name";Expression = {$_.SystemName}}, 
@{Label = "Drive Letter";Expression = {$_.DeviceID}}, 
@{Label = "Total Capacity (GB)";Expression = {"{0:N1}" -f( $_.Size / 1gb)}}, 
@{Label = "Free Space (GB)";Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) }}, 
@{Label = 'Free Space (%)'; Expression = {"{0:P0}" -f ($_.freespace/$_.size)}} | 
 
#Export report to CSV file (Disk Report) 
 
Export-Csv -path "C:\scripts\DiskReport_$logDate.csv" -NoTypeInformation 
  
#Send disk report using the exchange email module 
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; 
 
#Import-Module "\\Servername\ServerStorageReport\ExchangeModule\Exchange.ps1" -ErrorAction SilentlyContinue 
 
#Attach and send CSV report (Most recent report will be attached) 
 
$messageParameters = @{                         
                Subject = "Weekly Server Storage Report"                         
                Body = "Attached is Weekly Server Storage Report.All reports are located in C:\scripts\, but the most recent  is sent weekly"                    
                From = "Email name1 <[email protected]>"                         
                To = "Email name1 <[email protected]>" 
                CC = "Email name2 <[email protected]>" 
                Attachments = (Get-ChildItem C:\scripts\*.* | sort LastWriteTime | select -last 1)                    
                SmtpServer = "mail.example.com"                         
            }     
Send-MailMessage @messageParameters -BodyAsHtml

-----아래는 내 CSV의 모습입니다:

Servernames
server1
server2
server3
server4

답변1

알았어 이건 효과가 있었어:

$LogDate = get-date -f yyyyMMddhhmm
$File = Get-Content -Path C:\StorageReport\Servers.txt

$DiskReport = ForEach ($Servernames in ($File)) 

{Get-WmiObject win32_logicaldisk <#-Credential $RunAccount#> `
-ComputerName $Servernames -Filter "Drivetype=3" `
-ErrorAction SilentlyContinue 
} 

$DiskReport | 

Select-Object @{Label = "Server Name";Expression = {$_.SystemName}},
@{Label = "Drive Letter";Expression = {$_.DeviceID}},
@{Label = "Total Capacity (GB)";Expression = {"{0:N1}" -f( $_.Size / 1gb)}},
@{Label = "Free Space (GB)";Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) }},
@{Label = 'Free Space (%)'; Expression = {"{0:P0}" -f ($_.freespace/$_.size)}} |

Export-Csv -path "C:\StorageReport\DiskReport_$logDate.csv" -NoTypeInformation

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; 

$messageParameters = @{                        
                Subject = "Weekly Server Storage Report"                        
                Body = "Attached is Weekly Server Storage Report.All reports are located in C:\StorageReport\, but the                

          most recent  is sent weekly"                   
                From = "Email name1 <[email protected]>"                        
                To = "Email name1 <[email protected]>"
                CC = "Email name2 <[email protected]>"
                Attachments = (Get-ChildItem C:\StorageReport\*.* | sort LastWriteTime | select -last 1)                   
                SmtpServer = "SMTPServerName.com"                        
            }   
Send-MailMessage @messageParameters -BodyAsHtml

답변2

$Servers = Get-Content "C:\users\$env:username\desktop\input.txt"
$Drives = "C:","D:","E:"
 
$report = @()
 
#Looping each server
Foreach($Server in $Servers)
{
    $Server = $Server.trim()
    Write-Host "Processing $Server" -ForegroundColor Green
    Try
    {
        $Disks = Get-WmiObject -Class win32_logicaldisk -ComputerName $Server -ErrorAction Stop
    }
    Catch
    {
        $_.Exception.Message
        Continue
    }    
        If(!$Disks)
        {
            Write-Warning "Something went wrong"
        }
        Else
        {
            # Adding properties to object
            $Object = New-Object PSCustomObject
            $Object | Add-Member -Type NoteProperty -Name "ServerName" -Value $Server
         
            Foreach($Letter in $Drives)
            {
                Switch ($Letter)
                {
                    "C:"     { $Val = "OSDDisk (C:)"}
                    "D:"     { $Val = "Data (D:)"}
                    "E:"     { $Val = "Mountpoint_log (E:)"}
                }
 
                $FreeSpace = ($Disks | Where-Object {$_.DeviceID -eq "$Letter"} | Select-Object @{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}).freespace 
                If($FreeSpace)
                {
                    $Value = "$Freespace" + " GB"
                    $Object | Add-Member -Type NoteProperty -Name "$Val" -Value $Value   
                }
                Else
                {
                    $Object | Add-Member -Type NoteProperty -Name "$Val" -Value "(not found)"
                }
            }
            $report += $object
        }
} 
 
#Display results
return $report
 
#Save results to CSV file
$report | Export-Csv -Path C:\users\$env:username\desktop\free_space.csv -NoTypeInformation -Force
Share:

관련 정보