Optimieren Sie Ihr IT-Management: Meisterung des Hyper-V-Replikations-Monitoring mit PowerShell

Haupterkenntnisse

  • Automatisiertes Hyper-V-Replikations-Monitoring: Das Skript automatisiert den Prozess der Überwachung des Hyper-V-Replikationsstatus und verbessert die Effizienz im Management von virtuellen Umgebungen.
  • Anpassbare Alarm-Schwellenwerte: Administratoren können benutzerdefinierte Schwellenwerte für Replikationswarnungen mithilfe von Parametern wie –FailedFor festlegen.
  • Erhöhte Berechtigungen erforderlich: Die Ausführung des Skripts erfordert Administratorrechte für den Zugriff auf detaillierte VM-Replikationsinformationen.
  • Umgebungsspezifische Anpassungen: Verwenden Sie Umgebungsvariablen und benutzerdefinierte Felder, um die Funktionalität des Skripts an bestimmte IT-Umgebungen anzupassen.
  • Proaktives IT-Management-Tool: Das Skript dient als proaktives Tool für IT-Fachleute, das die rechtzeitige Erkennung und Lösung von Replikationsproblemen gewährleistet.
  • Verbessert gegenüber manuellen Methoden: Bietet einen umfassenderen und automatisierten Ansatz im Vergleich zu manuellen Kontrollen oder einfachen Skripten.
  • Integraler Bestandteil des IT-Infrastrukturmanagements: In Verbindung mit Plattformen wie NinjaOne bietet das Skript einen erheblichen Mehrwert für die Verwaltung und Sicherung der IT-Infrastruktur.
  • Erfordert PowerShell 5.1 oder eine neuere Version: Stellen Sie die Kompatibilität und Funktionalität mit der entsprechenden Version von PowerShell sicher.

Die effektive Verwaltung virtueller Umgebungen ist für IT-Experten von entscheidender Bedeutung, um optimale Leistung und Sicherheit zu gewährleisten. Ein wichtiger Aspekt dabei ist die Überwachung und Verwaltung der Hyper-V-Replikation, einer Funktion, die in virtualisierten Netzwerken zu Redundanz- und Failover-Zwecken weit verbreitet ist. Eine effiziente Überwachung des Hyper-V-Replikationsstatus gewährleistet die Geschäftskontinuität und Datenintegrität im Falle unerwarteter Ausfälle.

Hintergrund

Die Hyper-V-Replikation ist ein Mechanismus, mit dem virtuelle Maschinen (VMs ) von einem Hyper-V-Host auf einen anderen repliziert werden können, was eine wichtige Lösung für die Notfallwiederherstellung darstellt. IT-Experten und Managed Service Provider (MSPs ) benötigen robuste Tools zur Überwachung dieses Replikationsprozesses. Das Skript, über das wir sprechen, dient genau diesem Zweck: Es ermöglicht Administratoren, den Zustand und Status von VM-Replikationen effizient zu verfolgen und schnell auf Anomalien zu reagieren.

Das Skript:

#Requires -Version 5.1

<#
.SYNOPSIS
    This will get information about the current status of Hyper-V Replication. If its abnormal it'll check the last replication time to see if it should alert on it.
.DESCRIPTION
    This will get information about the current status of Hyper-V Replication. If its abnormal it'll check the last replication time to see if it should alert on it.
.EXAMPLE 
    (No Parameters)
    Replication is currently failing!
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorExcep 
   tion
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio 
   n,customscript_gen_2.ps1
 

    VMName      PrimaryServer            State   Health LastReplicationTime 
    ------      -------------            -----   ------ ------------------- 
    WIN10-TEST  SRV16-TEST.test.lan      Error Critical 4/13/2023 8:20:11 AM
    Win10-TEST2 SRV16-TEST.test.lan      Error Critical 4/13/2023 8:20:11 AM

PARAMETER: -FailedFor "30"
    Time in minutes any given vm replication is allowed to be abnormal.
    Ex. "20" will alert on a vm replication after its been in the abnormal state for 20 minutes.
.EXAMPLE
    -FailedFor "20"
    WARNING: Some of the vm's currently have replication paused!
 

    VMName      PrimaryServer                  State  Health LastReplicationTime 
    ------      -------------                  -----  ------ ------------------- 
    WIN10-TEST  SRV16-TEST.test.lan      Replicating  Normal 4/13/2023 8:40:04 AM
    Win10-TEST2 SRV16-TEST.test.lan        Suspended Warning 4/13/2023 8:32:06 AM

PARAMETER: -IncludePaused
    Script will consider paused vm's abnormal if this parameter is used.    
.EXAMPLE
    -IncludePaused
    Replication is currently failing!
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorExcep 
   tion
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorExceptio 
   n,customscript_gen_2.ps1
 

    VMName      PrimaryServer                  State  Health LastReplicationTime 
    ------      -------------                  -----  ------ ------------------- 
    WIN10-TEST  SRV16-TEST.test.lan      Replicating  Normal 4/13/2023 8:40:04 AM
    Win10-TEST2 SRV16-TEST.test.lan        Suspended Warning 4/13/2023 8:32:06 AM

PARAMETER: -FromCustomField "ReplaceMeWithAnyIntegerCustomField"
    Name of an integer custom field that contains your desired FailedFor threshold.
    ex. "ReplicationAlertThreshold" where you have entered in your desired alert limit in the "ReplicationAlertThreshold" custom field rather than in a parameter.
.EXAMPLE
    -FromCustomField "ReplaceMeWithAnyIntegerCustomField"
    WARNING: Some of the vm's currently have replication paused!
 

    VMName      PrimaryServer                  State  Health LastReplicationTime 
    ------      -------------                  -----  ------ ------------------- 
    WIN10-TEST  SRV16-TEST.test.lan      Replicating  Normal 4/13/2023 8:40:04 AM
    Win10-TEST2 SRV16-TEST.test.lan        Suspended Warning 4/13/2023 8:32:06 AM
.OUTPUTS
    None
.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).
#>

[CmdletBinding()]
param (
    [Parameter()]
    [int]$FailedFor = "60",
    [Parameter()]
    [String]$FromCustomField,
    [Parameter()]
    [Switch]$IncludePaused = [System.Convert]::ToBoolean($env:includePausedReplications)
)
begin {

    if ($env:allowedToFailForxMinutes -and $env:allowedToFailForxMinutes -notlike "null") { $FailedFor = $env:allowedToFailForxMinutes }
    if ($env:retrieveAllowedFailureTimeFromCustomField -and $env:retrieveAllowedFailureTimeFromCustomField -notlike "null" ) { $FromCustomField = $env:retrieveAllowedFailureTimeFromCustomField }

    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
    }

    # This function is to make it easier to parse Ninja Custom Fields.
    function Get-NinjaProperty {
        [CmdletBinding()]
        Param(
            [Parameter(Mandatory = $True, ValueFromPipeline = $True)]
            [String]$Name,
            [Parameter()]
            [String]$Type,
            [Parameter()]
            [String]$DocumentName
        )

        # If we're requested to get the field value from a Ninja document we'll specify it here.
        $DocumentationParams = @{}
        if ($DocumentName) { $DocumentationParams["DocumentName"] = $DocumentName }

        # These two types require more information to parse.
        $NeedsOptions = "DropDown","MultiSelect"

        # Grabbing document values requires a slightly different command.
        if ($DocumentName) {
            # Secure fields are only readable when they're a device custom field
            if ($Type -Like "Secure") { throw "$Type is an invalid type! Please check here for valid types. https://ninjarmm.zendesk.com/hc/en-us/articles/16973443979789-Command-Line-Interface-CLI-Supported-Fields-and-Functionality" }

            # We'll redirect the error output to the success stream to make it easier to error out if nothing was found or something else went wrong.
            Write-Host "Retrieving value from Ninja Document..."
            $NinjaPropertyValue = Ninja-Property-Docs-Get -AttributeName $Name @DocumentationParams 2>&1

            # Certain fields require more information to parse.
            if ($NeedsOptions -contains $Type) {
                $NinjaPropertyOptions = Ninja-Property-Docs-Options -AttributeName $Name @DocumentationParams 2>&1
            }
        }
        else {
            # We'll redirect error output to the success stream to make it easier to error out if nothing was found or something else went wrong.
            $NinjaPropertyValue = Ninja-Property-Get -Name $Name 2>&1

            # Certain fields require more information to parse.
            if ($NeedsOptions -contains $Type) {
                $NinjaPropertyOptions = Ninja-Property-Options -Name $Name 2>&1
            }
        }

        # If we received some sort of error it should have an exception property and we'll exit the function with that error information.
        if ($NinjaPropertyValue.Exception) { throw $NinjaPropertyValue }
        if ($NinjaPropertyOptions.Exception) { throw $NinjaPropertyOptions }

        # This switch will compare the type given with the quoted string. If it matches, it'll parse it further; otherwise, the default option will be selected.
        switch ($Type) {
            "Attachment" {
                # Attachments come in a JSON format this will convert it into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Checkbox" {
                # Checkbox's come in as a string representing an integer. We'll need to cast that string into an integer and then convert it to a more traditional boolean.
                [System.Convert]::ToBoolean([int]$NinjaPropertyValue)
            }
            "Date or Date Time" {
                # In Ninja Date and Date/Time fields are in Unix Epoch time in the UTC timezone the below should convert it into local time as a datetime object.
                $UnixTimeStamp = $NinjaPropertyValue
                $UTC = (Get-Date "1970-01-01 00:00:00").AddSeconds($UnixTimeStamp)
                $TimeZone = [TimeZoneInfo]::Local
                [TimeZoneInfo]::ConvertTimeFromUtc($UTC, $TimeZone)
            }
            "Decimal" {
                # In ninja decimals are strings that represent a decimal this will cast it into a double data type.
                [double]$NinjaPropertyValue
            }
            "Device Dropdown" {
                # Device Drop-Downs Fields come in a JSON format this will convert it into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Device MultiSelect" {
                # Device Multi-Select Fields come in a JSON format this will convert it into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Dropdown" {
                # Drop-Down custom fields come in as a comma-separated list of GUIDs; we'll compare these with all the options and return just the option values selected instead of a GUID.
                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header "GUID", "Name"
                $Options | Where-Object { $_.GUID -eq $NinjaPropertyValue } | Select-Object -ExpandProperty Name
            }
            "Integer" {
                # Cast's the Ninja provided string into an integer.
                if($NinjaPropertyValue){
                    [int]$NinjaPropertyValue
                }else{
                    $NinjaPropertyValue
                }
            }
            "MultiSelect" {
                # Multi-Select custom fields come in as a comma-separated list of GUID's we'll compare these with all the options and return just the option values selected instead of a guid.
                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header "GUID", "Name"
                $Selection = ($NinjaPropertyValue -split ',').trim()

                foreach ($Item in $Selection) {
                    $Options | Where-Object { $_.GUID -eq $Item } | Select-Object -ExpandProperty Name
                }
            }
            "Organization Dropdown" {
                # Turns the Ninja provided JSON into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Organization Location Dropdown" {
                # Turns the Ninja provided JSON into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Organization Location MultiSelect" {
                # Turns the Ninja provided JSON into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Organization MultiSelect" {
                # Turns the Ninja provided JSON into a PowerShell Object.
                $NinjaPropertyValue | ConvertFrom-Json
            }
            "Time" {
                # Time fields are given as a number of seconds starting from midnight. This will convert it into a datetime object.
                $Seconds = $NinjaPropertyValue
                $UTC = ([timespan]::fromseconds($Seconds)).ToString("hh\:mm\:ss")
                $TimeZone = [TimeZoneInfo]::Local
                $ConvertedTime = [TimeZoneInfo]::ConvertTimeFromUtc($UTC, $TimeZone)

                Get-Date $ConvertedTime -DisplayHint Time
            }
            default {
                # If no type was given or not one that matches the above types just output what we retrieved.
                $NinjaPropertyValue
            }
        }
    }
}
process {
    if ($FromCustomField) {
        try{
            $CustomFieldValue = Get-NinjaProperty -Name $FromCustomField -Type "Integer"
        }catch{
            Write-Warning "$($_.ToString())"
        }

        if($CustomFieldValue){
            $FailedFor = $CustomFieldValue
        }else{
            Write-Warning "Custom Field $FromCustomField was empty?"
        }
    }

    if($FailedFor -gt 0){
        $FailedFor = $FailedFor * -1
    }

    $Threshold = (Get-Date).AddMinutes($FailedFor)
    Write-Host "Checking vm's that have not replicated prior to $Threshold."

    $Failed = New-Object System.Collections.Generic.List[string]
    $UnhealthyVMs = Get-VMReplication | Where-Object { $_.Health -notlike "Normal" -and $_.LastReplicationTime -lt $Threshold -and $_.State -notlike "Suspended" }
    $PausedVMs = Get-VMReplication | Where-Object { $_.LastReplicationTime -lt $Threshold -and $_.State -like "Suspended" }

    if ($UnhealthyVMs) {
        $Failed.Add($UnhealthyVMs)
    }
    
    if ($PausedVMs) {
        Write-Warning "Some of the vm's currently have replication paused!"

        if(-not $IncludePaused){
            Write-Warning "Please use 'Include Paused Replications' to include paused replications in the alert. Otherwise, they will be skipped."
        }
    }

    if ($PausedVMs -and $IncludePaused) {
        $Failed.Add($PausedVMs)
    }

    if ($Failed) {
        Write-Error "Hyper-V Replication is currently failing!"
        Get-VMReplication | Format-Table -Property VMName, PrimaryServer, State, Health, LastReplicationTime | Out-String | Write-Host
        exit 1
    }
    else {
        Write-Host "No failing replications detected prior to $Threshold."

        Get-VMReplication | Format-Table -Property VMName, PrimaryServer, State, Health, LastReplicationTime | Out-String | Write-Host
        exit 0
    }
}end {
    
    
    
}

 

Zugriff auf über 300 Skripte im NinjaOne Dojo

Zugang erhalten

Detaillierte Aufschlüsselung

Das Skript ist ein PowerShell-Dienstprogramm zur Überwachung des Status der Hyper-V-Replikation. Es prüft den Replikationsstatus und den Zustand jeder VM und alarmiert die Administratoren, wenn es Probleme gibt. Die wichtigsten Bestandteile des Drehbuchs sind:

  • Cmdlet-Bindung und Parameter: Das Skript verwendet erweiterte Funktionen, die Parameter wie -FailedFor, -FromCustomField und -IncludePausedzulassen.
  • Umgebungsvariablen und Funktionen: Es verwendet benutzerdefinierte Funktionen und Umgebungsvariablen, um erhöhte Berechtigungen zu bestimmen und benutzerdefinierte Feldwerte abzurufen.
  • Hauptprozess: Das Skript bewertet den Zustand und die Zeit der Replikation jeder VM und vergleicht sie mit den festgelegten Schwellenwerten. Wenn eine VM nicht innerhalb des festgelegten Zeitrahmens repliziert wurde oder sich in einem anormalen Zustand befindet, wird ein Alarm ausgelöst.

Dieses Skript könnte visuell in einem Flussdiagramm dargestellt werden, in dem die Schritte von der Initialisierung, der Parametereinstellung, der Berechtigungsprüfung bis hin zur abschließenden Analyse und Alarmierung detailliert beschrieben werden.

Mögliche Anwendungsfälle

Stellen Sie sich einen IT-Administrator in einem mittelgroßen Unternehmen mit einer stabilen virtualisierten Umgebung unter Hyper-V vor. Er würde dieses Skript einsetzen, um den VM-Replikationsstatus regelmäßig zu überwachen, etwaige Replikationsprobleme schnell zu erkennen und zu beheben und so die Geschäftskontinuität sicherzustellen.

Vergleiche

Die Überwachung der Hyper-V-Replikation erfolgt in der Regel durch manuelle Prüfungen oder weniger ausgefeilte Skripte. Dieses Skript automatisiert jedoch den Prozess und bietet eine umfassendere und anpassbare Überwachung. Es übertrifft einfache PowerShell-Befehle oder manuelle GUI-Prüfungen an Effizienz und Skalierbarkeit.

FAQs

F: Kann dieses Skript auf jeder Version von PowerShell ausgeführt werden?
A: Es erfordert PowerShell 5.1 oder höher.

F: Ist es notwendig, das Skript mit Administratorrechten auszuführen?
A: Ja, das Skript prüft auf erhöhte Rechte, da es Zugriff auf VM-Replikationsdetails benötigt.

F: Wie kann ich die Alarmschwelle anpassen?
A: Verwenden Sie den Parameter -FailedFor, um einen benutzerdefinierten Zeitrahmen in Minuten festzulegen.

Auswirkungen

Während dieses Skript die Überwachung der Hyper-V-Replikation verbessert, unterstreicht es auch die Notwendigkeit proaktiver IT-Sicherheitsmaßnahmen. Die rechtzeitige Erkennung und Behebung von Replikationsproblemen ist entscheidend für die Aufrechterhaltung der Datenintegrität und -verfügbarkeit.

Empfehlungen

  • Führen Sie das Skript regelmäßig aus, um eine kontinuierliche Überwachung zu gewährleisten.
  • Passen Sie den Parameter -FailedFor an die spezifischen Anforderungen der Umgebung an.
  • Stellen Sie sicher, dass PowerShell 5.1 oder höher installiert ist und mit den erforderlichen Berechtigungen ausgeführt wird.

Abschließende Überlegungen

Im Zusammenhang mit der Verwaltung virtualisierter Umgebungen bieten Tools wie NinjaOne eine umfassende Plattform für die Überwachung und Verwaltung der IT-Infrastruktur. Die Einbindung eines solchen Skripts in eine größere Suite von NinjaOne-Tools kann die Fähigkeit eines Unternehmens verbessern, Hyper-V-Umgebungen effizient zu verwalten und Zuverlässigkeit und Leistung zu gewährleisten.

Nächste Schritte

Der Aufbau eines effizienten und effektiven IT-Teams erfordert eine zentralisierte Lösung, die als vereintes Tool für die Bereitstellung von Dienstleistungen fungiert. NinjaOne ermöglicht es IT-Teams, all ihre Geräte zu überwachen, verwalten, sichern und zu unterstützen, unabhängig von ihrem Ort und komplexer Infrastruktur vor Ort.

Erfahren Sie mehr über NinjaOne Endpoint Management schauen Sie sich eine Live-Tour an oder starten Sie Ihre kostenlose Testversion der NinjaOne Plattform.

Kategorien:

Das könnte Sie auch interessieren

Demo ansehen×
×

Sehen Sie NinjaOne in Aktion!

Mit dem Absenden dieses Formulars akzeptiere ich die Datenschutzerklärung von NinjaOne.

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).