Difference between revisions of "PowerShell Scripts"

From Hostek.com Wiki
Jump to: navigation, search
(Disk Usage Warning)
(GZip All Files in Directory)
Line 41: Line 41:
  
 
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.
 
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.
 +
 +
Optional parameter '''Days''' specifies how many days old a file must be in order to be gzipped.  This is useful for log folders where you may want the last couple days to remain unzipped
 +
 +
Option switch '''-Recurse''' allows the script to include all sub-directories.
  
 
<syntaxhighlight lang="powershell">
 
<syntaxhighlight lang="powershell">
param(
+
param(
    [string]$Directory = $(throw 'Parameter ''Directory'' is required.')
+
    [string]$Directory = $(throw 'Parameter ''Directory'' is required.'),
)
+
    [int]$Days = 0,
+
    [switch]$Recurse = $false
if ($(Test-Path $Directory) -eq $false) {
+
)
    throw "Directory does not exist: $Directory"
+
 
}
+
$Date = [System.DateTime]::Now.AddDays($Days * -1)
+
 
foreach ($file in $(Get-ChildItem -Path $Directory|Where-Object {$_.Name -match '^(?!.*\.gz$)'})) {
+
if ($(Test-Path $Directory) -eq $false) {
    $fsFile = New-Object System.IO.FileStream ($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read);
+
    throw "Directory does not exist: $Directory"
    $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)
+
 
+
foreach ($file in $(Get-ChildItem -Path $Directory -File -Recurse:$Recurse|Where-Object {$_.Name -match '^(?!.*\.gz$)' -and $_.LastWriteTime -lt $Date})) {
    $gzipped = $false
+
    $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)
    try {
+
    $gzSream = New-Object System.IO.Compression.GzipStream ($fsGZip, [IO.Compression.CompressionMode]::Compress)
       
+
 
        $BUFFER_SIZE = 1024 * 256
+
    $gzipped = $false
        $buffer = New-Object byte[]($BUFFER_SIZE);
+
 
        $bytesRead = -1
+
    try {
+
       
        while ($bytesRead -ne 0) {
+
        $BUFFER_SIZE = 1024 * 256
            $bytesRead = $fsFile.Read($buffer, 0, $BUFFER_SIZE)
+
        $buffer = New-Object byte[]($BUFFER_SIZE);
            $gzSream.Write($buffer, 0, $bytesRead)
+
        $bytesRead = -1
        }
+
 
+
        while ($bytesRead -ne 0) {
        $gzipped = $true
+
            $bytesRead = $fsFile.Read($buffer, 0, $BUFFER_SIZE)
    }
+
            $gzSream.Write($buffer, 0, $bytesRead)
    finally {
+
        }
        $gzSream.Dispose();
+
 
        $fsGZip.Dispose();
+
        $gzipped = $true
        $fsFile.Dispose();
+
    }
    }
+
    finally {
+
        $gzSream.Dispose();
    if ($gzipped) {
+
        $fsGZip.Dispose();
        Remove-Item $file.FullName
+
        $fsFile.Dispose();
    }
+
    }
}
+
 
 +
    if ($gzipped) {
 +
        Remove-Item $file.FullName
 +
    }
 +
}
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
Example Usage:
 
Example Usage:
  
  powershell -File GZipDirContents.ps1 C:\FULL\PATH\TO\DIRECTORY
+
  powershell -File GZipDirContents.ps1 C:\FULL\PATH\TO\DIRECTORY 1 -Recurse
  
 
[[Category:VPS]]
 
[[Category:VPS]]

Revision as of 15:54, 31 May 2013

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.

Optional parameter Days specifies how many days old a file must be in order to be gzipped. This is useful for log folders where you may want the last couple days to remain unzipped

Option switch -Recurse allows the script to include all sub-directories.

param(
    [string]$Directory = $(throw 'Parameter ''Directory'' is required.'),
    [int]$Days = 0,
    [switch]$Recurse = $false
)
 
$Date = [System.DateTime]::Now.AddDays($Days * -1)
 
if ($(Test-Path $Directory) -eq $false) {
    throw "Directory does not exist: $Directory"
}
 
foreach ($file in $(Get-ChildItem -Path $Directory -File -Recurse:$Recurse|Where-Object {$_.Name -match '^(?!.*\.gz$)' -and $_.LastWriteTime -lt $Date})) {
    $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 1 -Recurse