0

I am required to get reports about free disk space on our exchange servers. I found this link : https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Script-Sample-f7164554

But I am unable to successfully run it...anybody got a better/easier way to do this? I don't need the report as email...just as a csv file. I'm using windows 10..and $PSVersionTable shows:

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

The Error I get:

-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

Same for -ComputerName however the weird thing is that it still runs and creates the csv file but instead of 4 servers it has the disk size listings of only the localhost

I was able to make this script send the email and I can use task cheduler to run it weekly, Just need to figure out this error and Why its displaying only one server(locolhost) disk size. Here's the exact script I used:

$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 <admin@example.com>"                         
                To = "Email name1 <admin@example.com>" 
                CC = "Email name2 <user@example.com>" 
                Attachments = (Get-ChildItem C:\scripts\*.* | sort LastWriteTime | select -last 1)                    
                SmtpServer = "mail.example.com"                         
            }     
Send-MailMessage @messageParameters -BodyAsHtml

-----Below is what my csv looks like:

Servernames
server1
server2
server3
server4
David Kent
  • 37
  • 1
  • 6
  • PLEASE, read the Tour page for this site. that explains the rules that your post violates. [*grin*] ///// also, please, add the version of windows and powershell that you are using to your Question, what did not work as needed - in detail, and any errors you get back. – Lee_Dailey Aug 25 '20 at 13:47
  • @Lee_Dailey I added the details – David Kent Aug 26 '20 at 04:50
  • 1
    You added a tiny part of the details. Why do you not add the **complete error message** and the **complete $PSVersionTable output**? – Daniel Aug 26 '20 at 06:19
  • Why use powershell when you can use the old "dir" command? – Overmind Aug 26 '20 at 06:26
  • Also add the command exactly as you executed it. Most probably you have a typo in the parameters. – Gerald Schneider Aug 26 '20 at 07:24
  • @Lee_Dailey I get your point...I will update my question after a few hours and mention every detail...thanks...don't give up on me.....i need to execute this :D – David Kent Aug 26 '20 at 09:41
  • @DavidKent - that error about the `-ComputerName` parameter is one that often happens when copying stuff from a doc file OR from a web page. paste the code into a new ISE session and look carefully for the red squiggles that indicate an error. the poster of that code use **_backticks_** [eeewwwwwww!!!!] and they are notorious for being left behind. i suspect that you simply need to re-arrange that line so that backticks are not needed - making it one line ending with the '|' symbol. – Lee_Dailey Aug 26 '20 at 13:37
  • @Lee_Dailey backticks ??? And please check this script now...I added the first line of the script bcz I dont get it how else it will get the servernames from ?? – David Kent Aug 27 '20 at 05:58
  • @DavidKent - the tiny slanted mark at the end of the `Get-WmiObject win32_logicaldisk` line is a backtick. it's used to wrap lines ... and is very often missed when copying code. ///// `$Servernames` is the temp variable in the `foreach` loop that holds the current item from the `$Files` list. ///// since you get the error with both of those parameters, then it's the backtick that is the problem ... **_the version you posted has a space after the backtick. that means it is NOT escaping the "end of line", but is instead escaping the space. that means the two params are not part of the command. – Lee_Dailey Aug 27 '20 at 13:37
  • @Lee_Dailey I updated the question, how can i add a blank line to the csv generated ?? – David Kent Aug 28 '20 at 21:42
  • @DavidKent - CSV files don't have such. [*grin*] if you want to visually divide the server groups, you will likely need to either add the blank lines via code [perhaps with a filter of some sort], OR program your HTML to do that for you, OR divide the files into per-server files, OR do something else. ///// this is far, far, far off the original topic. i suggest you create a new Question that shows what you have, what you want, what you have tried, and - finally - what did not work as wanted. – Lee_Dailey Aug 28 '20 at 23:45
  • @Lee_Dailey ok thanks...i will post it as a new question...cheers. – David Kent Aug 30 '20 at 04:59
  • @DavidKent - you are very welcome! glad to help a bit ... and good luck! [*grin*] – Lee_Dailey Aug 30 '20 at 13:30

2 Answers2

0

ok this worked :

$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.name1@domainname.com>"                        
                To = "Email name1 <Email.name1@domainname.com>"
                CC = "Email name2 <Email.name2@domainname.com>"
                Attachments = (Get-ChildItem C:\StorageReport\*.* | sort LastWriteTime | select -last 1)                   
                SmtpServer = "SMTPServerName.com"                        
            }   
Send-MailMessage @messageParameters -BodyAsHtml
David Kent
  • 37
  • 1
  • 6
0
$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:
Andrew Schulman
  • 8,811
  • 21
  • 32
  • 47
hussains8
  • 101
  • 1