PowerShell Scripts
From Hostek.com Wiki
This is a repository of PowerShell Scripts for server management tasks.
Disk Usage Warning
This script allows you to send an e-mail if disk free-space is below a particular percentage.
#SETTINGS $Computers = 'server1' # multiple servers should be formmated: 'server1', 'server2', 'server3'. The user executing this script must have administrative access to all servers. $WarnPercentage = 15 $SmtpHost = 'mail.domainname.com' $SmtpPort = 25 $FromAddress = 'disk-monitor@domainname.com' $Recipients = 'admin@domainname.com' # multiple recipients should be separated with commas: 'user1@domainname.com,user2@domainname.com,user3@domainname.com' #SETTINGS #GET DISK OVERAGES $Overages = Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3" -ComputerName $Computers| ` Where { (100 * ($_.FreeSpace / $_.Size)) -le $WarnPercentage }| ` Select SystemName, DeviceID, @{ Name="FreeSpace(GB)"; Expression={"{0:N}" -f ($_.FreeSpace / 1GB) }} $OverageCount = @($Overages).Length #GET DISK OVERAGES if ($OverageCount -gt 0) { #SEND EMAIL $Subject = "$OverageCount drives are below $WarnPercentage% free space" $Body = "Warning, the following drives are below $WarnPercentage% free space:`r`n`r`n$($Overages|Out-String -Width 80)" $SmtpClient = New-Object System.Net.Mail.SmtpClient($SmtpHost, $SmtpPort) $SmtpClient.Send($FromAddress, $Recipients, $Subject, $Body) $SmtpClient.Dispose() #SEND EMAIL }
Example Usage:
powershell -File CheckDiskUsage.ps1
GZip All Files in Directory
This script will gzip compress all files within a folder. The original file will be replaced with a .gz file starting with the same name. This can be useful for compressing SQL backups or Log files on a schedule.
param( [string]$Directory = $(throw 'Parameter ''Directory'' is required.') ) if ($(Test-Path $Directory) -eq $false) { throw "Directory does not exist: $Directory" } foreach ($file in $(Get-ChildItem -Path $Directory|Where-Object {$_.Name -match '^(?!.*\.gz$)'})) { $fsFile = New-Object System.IO.FileStream ($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read); $fsGZip = New-Object System.IO.FileStream ("$($file.FullName).gz", [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) $gzSream = New-Object System.IO.Compression.GzipStream ($fsGZip, [IO.Compression.CompressionMode]::Compress) $gzipped = $false try { $BUFFER_SIZE = 1024 * 256 $buffer = New-Object byte[]($BUFFER_SIZE); $bytesRead = -1 while ($bytesRead -ne 0) { $bytesRead = $fsFile.Read($buffer, 0, $BUFFER_SIZE) $gzSream.Write($buffer, 0, $bytesRead) } $gzipped = $true } finally { $gzSream.Dispose(); $fsGZip.Dispose(); $fsFile.Dispose(); } if ($gzipped) { Remove-Item $file.FullName } }
Example Usage:
powershell -File GZipDirContents.ps1 C:\FULL\PATH\TO\DIRECTORY