How to Automate Hyper-V Checkpoint Alerts Using PowerShell

Managing Hyper-V environments efficiently is a critical task for IT professionals and Managed Service Providers (MSPs). One aspect of this management involves keeping track of checkpoints, which are essential for maintaining system states and ensuring smooth recovery processes. This blog post will explore a PowerShell script designed to automate the process of monitoring and alerting administrators about Hyper-V checkpoints that exceed a certain age threshold.

Understanding the Script’s Purpose and Importance

The provided PowerShell script is a valuable tool for IT administrators who need to ensure that their Hyper-V environments remain clean and efficient. Checkpoints, also known as snapshots, capture the state of a virtual machine at a specific point in time. While they are useful for backups and recovery, old checkpoints can consume significant storage space and potentially affect VM performance. Therefore, regularly monitoring and managing these checkpoints is crucial.

The Script

#Requires -Version 5.1

<#
.SYNOPSIS
    This will get information about the current number of Hyper-V checkpoints there are on a given machine. Can be given a threshold in days to report on, can also get this threshold from an integer custom field.
.DESCRIPTION
    This will get information about the current number of Hyper-V checkpoints there are on a given machine. 
    Can be given a threshold in days to report on, can also get this threshold from an integer custom field.

.EXAMPLE 
    (No Parameters)
    WARNING: There are checkpoints older than 04/12/2023 14:01:26!

    VMName              Name                   CreationTime
    ------              ----                   ------------
    SRV16-TEST          Fresh Start            4/12/2023 10:53:14 AM
    SRV16-TEST          Hyper-V Installed      4/12/2023 11:13:09 AM
    SRV19-TEST          Fresh Start            4/12/2023 10:42:44 AM
    SRV22-TEST          Fresh Start            4/12/2023 10:45:02 AM

PARAMETER: -OlderThan "14"
    Alert/Show only vm checkpoints older than x days. 
    ex. "7" will alert/show vm checkpoints older than 7 days.
.EXAMPLE
    -OlderThan "7"
    WARNING: There are checkpoints older than 04/05/2023 14:04:01!
    
    VMName              Name                                                              CreationTime
    ------              ----                                                              ------------
    old WIN10-TEST      Automatic Checkpoint - WIN10-TEST - (3/30/2023 - 3:02:28 PM)      3/30/2023 3:02:28 PM 

PARAMETER: -FromCustomField "ReplaceMeWithAnyIntegerCustomField"
    Name of an integer custom field that contains your desired OlderThan threshold.
    ex. "CheckpointAgeLimit" where you have entered in your desired age limit in the "CheckPointAgeLimit" custom field rather than in a parameter.
.EXAMPLE
    -FromCustomField "ReplaceMeWithAnyIntegerCustomField"
    WARNING: There are checkpoints older than 04/05/2023 14:04:01!
    
    VMName              Name                                                              CreationTime
    ------              ----                                                              ------------
    old WIN10-TEST      Automatic Checkpoint - WIN10-TEST - (3/30/2023 - 3:02:28 PM)      3/30/2023 3:02:28 PM

.OUTPUTS
    
.NOTES
    Minimum OS Architecture Supported: Windows 10, Server 2016
    Release Notes: Renamed script and added Script Variable support
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.COMPONENT
    ManageUsers
#>

[CmdletBinding()]
param (
    [Parameter()]
    [int]$OlderThan = "0",
    [Parameter()]
    [String]$FromCustomField
)
begin {
    if ($env:ageLimit -and $env:ageLimit -notlike "null") { $OlderThan = $env:ageLimit }
    if ($env:retrieveAgeLimitFromCustomField -and $env:retrieveAgeLimitFromCustomField -notlike "null") { $FromCustomField = $env:retrieveAgeLimitFromCustomField }

    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    function Test-IsSystem {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        return $id.Name -like "NT AUTHORITY*" -or $id.IsSystem
    }

    if (!(Test-IsElevated) -and !(Test-IsSystem)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
}
process {

    $Threshold = (Get-Date).AddDays(-$OlderThan)

    if ($FromCustomField) {
        $Threshold = (Get-Date).AddDays( - (Ninja-Property-Get $FromCustomField))
    }
    
    $CheckPoints = Get-VM | Get-VMSnapshot | Where-Object { $_.CreationTime -lt $Threshold }

    if (!$CheckPoints) {
        Write-Host "There are no checkpoints older than $Threshold!"
        exit 0
    }
    else {
        Write-Warning "There are checkpoints older than $Threshold!"
        $Checkpoints | Format-Table -Property VMName, Name, CreationTime | Out-String | Write-Host
        exit 1
    }
}end {
    
    
    
}

 

Access over 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown of the Script

The script begins by specifying that it requires PowerShell version 5.1. It includes a .SYNOPSIS section explaining its purpose: to gather information about Hyper-V checkpoints on a given machine, with an optional threshold parameter to filter checkpoints older than a specified number of days. The script also accepts an integer custom field to determine this threshold.

Example Usage:

  • Without parameters: Displays all checkpoints older than a default threshold.
  • With -OlderThan parameter: Filters checkpoints older than the specified number of days.
  • With -FromCustomField parameter: Uses a custom field to determine the threshold.

Parameter Definitions

The script accepts two parameters:

  • -OlderThan [int]: Specifies the number of days to use as the threshold.
  • -FromCustomField [string]: Specifies the name of a custom field containing the threshold value.

Beginning Phase: Environment Checks

The begin block of the script sets up environment checks and functions to determine if the script is running with elevated privileges or as the system account. This ensures that the script can access necessary resources and perform its tasks without permission issues.

Functions Defined:

  • Test-IsElevated: Checks if the script is running with Administrator privileges.
  • Test-IsSystem: Checks if the script is running as the system account.

If neither condition is met, the script exits with an error message, ensuring it runs in a secure context.

Processing Phase: Checkpoint Filtering

In the process block, the script calculates the threshold date based on the OlderThan parameter or the value from the custom field. It retrieves all Hyper-V checkpoints and filters them based on their creation time, comparing it to the threshold date.

Key Operations:

  • Get-VM | Get-VMSnapshot | Where-Object { $_.CreationTime -lt $Threshold }: Retrieves and filters checkpoints older than the threshold date.
  • Displays a warning if older checkpoints are found, listing their details (VM name, checkpoint name, creation time).
  • Exits with a status code indicating whether old checkpoints were found.

Potential Use Cases

Imagine an IT professional managing a large Hyper-V environment with multiple virtual machines. They need to ensure that checkpoints older than 30 days are reviewed and deleted to maintain optimal performance and storage usage. By running this script with the -OlderThan 30 parameter, they can quickly identify and address outdated checkpoints, preventing potential issues before they escalate.

Comparisons with Other Methods

Traditional methods of managing Hyper-V checkpoints involve manually checking each virtual machine, which is time-consuming and prone to errors. In contrast, this PowerShell script automates the process, providing a quick and reliable way to monitor checkpoints. Other solutions may include third-party management tools, but these can be costly and require additional training.

Frequently Asked Questions

Q: Can this script be run on any Windows OS?

A: The script supports Windows 10 and Server 2016 or later.

Q: What happens if the script finds no old checkpoints?

A: It will display a message indicating no checkpoints are older than the specified threshold and exit with a status code of 0.

Q: How do I use a custom field for the threshold?

A: Specify the custom field name with the -FromCustomFieldparameter. Ensure the field contains the desired threshold value in days.

Implications for IT Security and Efficiency

Regularly monitoring and managing Hyper-V checkpoints can significantly enhance system performance and security. By identifying and addressing outdated checkpoints, IT professionals can prevent storage bloat and potential performance degradation. Automated scripts like this one ensure consistent and efficient checkpoint management, freeing up administrators to focus on more critical tasks.

Best Practices for Using the Script

  • Run the script with administrative privileges to ensure proper access to all necessary resources.
  • Schedule the script to run at regular intervals using Task Scheduler for continuous monitoring.
  • Review and adjust the OlderThan threshold based on your environment’s specific needs.

Final Thoughts

Efficiently managing Hyper-V checkpoints is essential for maintaining optimal performance and security in virtualized environments. This PowerShell script provides a powerful, automated solution for monitoring and alerting administrators about outdated checkpoints. By integrating such tools into their workflows, IT professionals can ensure their systems remain clean, efficient, and secure.

NinjaOne offers a range of tools and features that can further enhance your IT management processes, providing a comprehensive solution for monitoring, automation, and maintenance tasks. Incorporating NinjaOne with scripts like this can streamline your operations and improve overall efficiency.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).