Demo ansehen×
×

Sehen Sie NinjaOne in Aktion!

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

Wie Sie Ihren Festplattenspeicher per Fernzugriff mit PowerShell überwachen und verwalten können

Die Überwachung des Festplattenspeichers ist eine grundlegende, aber zentrale Komponente des proaktiven IT-Supports, die für die Reduzierung des Ticketvolumens und die Aufrechterhaltung der Systemgesundheit und -stabilität entscheidend ist. Wenn der Speicherplatz knapp wird oder zur Neige geht, kann dies zu einer Vielzahl von Problemen und Benutzerbeschwerden führen – von Anwendungsfehlern bis hin zu kompletten Systemabstürzen -, so dass die Erstellung von Warnmeldungen, wenn der Speicherplatz unter einen bestimmten Schwellenwert fällt, eine gute Möglichkeit ist, diese Probleme zu vermeiden. In diesem Beitrag erfahren Sie, wie Sie die Festplattenkapazität überprüfen und per Fernzugriff eine Warnung bei geringem Speicherplatz für Ihre gesamte Benutzerbasis ausgeben können. Wie kann ich den Festplattenspeicher aus der Ferne überprüfen und eine Warnung senden, wenn der Speicherplatz knapp wird?

  1. Legen Sie fest, welche Laufwerke Sie überwachen wollen und welche (falls vorhanden) Sie ausschließen wollen.
  2. Bestimmen Sie die Schwellenwerte für den Festplattenspeicher, die Sie für jede Art von Laufwerk festlegen möchten.
  3. Passen Sie das folgende Skript entsprechend an.

Dieses PowerShell-Skript ist darauf ausgelegt, auf Laufwerke hinzuweisen, die einen bestimmten Prozentsatz oder eine bestimmte Größe unterschreiten. Es unterscheidet zwischen Systemlaufwerken (die zum Booten des Betriebssystems verwendet werden) und Datenlaufwerken und bietet so einen umfassenden Überblick über die Nutzung des Speicherplatzes. Das Skript ist vielseitig und anpassbar, so dass Sie die Parameter für System- und Datenlaufwerke getrennt einstellen können. Sie können den minimalen freien Speicherplatz sowohl in Prozent als auch in Bytes angeben und sogar bestimmte Laufwerke von der Prüfung ausschließen. Diese Flexibilität ist ideal für jeden IT-Experten oder MSP.

Das Skript Disk Space Monitor:

#Requires -Version 2.0

<#
.SYNOPSIS
    Alert on drive(s) that fall below a specified % or size. Distinguishes between System and Data drives.
.DESCRIPTION
    Alert on drive(s) that fall below a specified % or size. Distinguishes between System and Data drives.
    The system drive is the drive(s) that are used to boot the OS.
.EXAMPLE
     -SystemDriveMinFreePercent 10 -SystemDriveMinFreeBytes 10GB -DataDriveMinFreePercent 20 -DataDriveMinFreeBytes 20GB
    This checks all Drives
.EXAMPLE
     -ExcludeDrivesCustomField "C,Z" -SystemDriveMinFreePercentCustomField "SystemDriveMinFreePercent" -SystemDriveMinFreeBytes "SystemDriveMinFreeBytes" -DataDriveMinFreePercent "DataDriveMinFreePercent" -DataDriveMinFreeBytes "DataDriveMinFreeBytes"
    This checks all Drives, except for C: and Z:.
    Use this if you wish to to custom fields to specify the values from roles or globally.
    This will pull the values from custom fields that would have otherwise been used from parameters.
.EXAMPLE
     -ExcludeDrivesByNameCustomField "NoMonitor" -SystemDriveMinFreePercentCustomField "SystemDriveMinFreePercent" -SystemDriveMinFreeBytes "SystemDriveMinFreeBytes" -DataDriveMinFreePercent "DataDriveMinFreePercent" -DataDriveMinFreeBytes "DataDriveMinFreeBytes"
    This checks all Drives, except where a drive name/label contains the text "NoMonitor".
    Use this if you wish to to custom fields to specify the values from roles or globally.
    This will pull the values from custom fields that would have otherwise been used from parameters.
.EXAMPLE
     No Parameters Specified
    This checks all Drives with the defaults:
        SystemDriveMinFreePercent   10%
        SystemDriveMinFreeBytes     10GB
        DataDriveMinFreePercent 20%
        DataDriveMinFreeBytes   20GB
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 7, Windows Server 2012 R2
    Release Notes:
    Initial Release
    (c) 2023 NinjaOne
    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()]
    [String]
    $ExcludeDrives,
    $ExcludeDrivesCustomField, # If set, get value from a custom field with this name.
    [String]
    $ExcludeDrivesByName,
    $ExcludeDrivesByNameCustomField, # If set, get value from a custom field with this name.
    $SystemDriveMinFreePercent = 10,
    $SystemDriveMinFreePercentCustomField, # If set, get value from a custom field with this name.
    $SystemDriveMinFreeBytes = 10GB,
    $SystemDriveMinFreeBytesCustomField, # If set, get value from a custom field with this name.
    $DataDriveMinFreePercent = 20,
    $DataDriveMinFreePercentCustomField, # If set, get value from a custom field with this name.
    $DataDriveMinFreeBytes = 20GB,
    $DataDriveMinFreeBytesCustomField # If set, get value from a custom field with this name.
)

begin {
    function Get-Size {
        param (
            [string]$String
        )
        switch -wildcard ($String) {
            '*PB' { [int64]$($String -replace '[^d+]+') * 1PB; break }
            '*TB' { [int64]$($String -replace '[^d+]+') * 1TB; break }
            '*GB' { [int64]$($String -replace '[^d+]+') * 1GB; break }
            '*MB' { [int64]$($String -replace '[^d+]+') * 1MB; break }
            '*KB' { [int64]$($String -replace '[^d+]+') * 1KB; break }
            '*B' { [int64]$($String -replace '[^d+]+') * 1; break }
            '*Bytes' { [int64]$($String -replace '[^d+]+') * 1; break }
            Default { [int64]$($String -replace '[^d+]+') * 1 }
        }
    }
    function Get-FriendlySize {
        param($Bytes)
        # Converts Bytes to the highest matching unit
        $Sizes = 'Bytes,KB,MB,GB,TB,PB,EB,ZB' -split ','
        for ($i = 0; ($Bytes -ge 1kb) -and ($i -lt $Sizes.Count); $i++) { $Bytes /= 1kb }
        $N = 2
        if ($i -eq 0) { $N = 0 }
        if ($Bytes) { "$([System.Math]::Round($Bytes,$N)) $($Sizes[$i])" }else { "0 B" }
    }
    function Invoke-DiskAlert {
        param (
            [PSObject[]]$Drives
        )
        $Drives | ForEach-Object {
            $Type = if ($_.IsSystemDrive) { "SystemDrive" }else { "DataDrive" }
            $Drive = $_
            if ($Drive.totalSpace -and $Drive.freeSpace / $Drive.totalSpace * 100 -lt $Settings."$Type".MinFreePercent) {
                Write-Output "$Type ($($Drive.driveName)) free space is under $($Settings."$Type".MinFreePercent)% at $(Get-FriendlySize -Bytes $Drive.freeSpace)"
            }
            elseif ($Drive.freeSpace -lt $Settings.$Type.MinFreeBytes) {
                Write-Output "$Type ($($Drive.driveName)) free space is under $(Get-FriendlySize -Bytes $Settings."$Type".MinFreeBytes) at $(Get-FriendlySize -Bytes $Drive.freeSpace)"
            }
        }
    }
    function Get-Drive {
        param([string]$DriveName)
        if ($(Get-Command -Name "Get-CimInstance")) {
            Get-CimInstance -Query "select * from Win32_DiskDrive" | Where-Object { $_.Size } | ForEach-Object {
                $d = $_
                $d | ForEach-Object {
                    $Disk = $_
                    $p = Get-CimInstance -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='$($Disk.DeviceID)'}  WHERE AssocClass = Win32_DiskDriveToDiskPartition"
                    $p | ForEach-Object {
                        $Partition = $_
                        Get-CimInstance -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='$($Partition.DeviceID)'} WHERE AssocClass = Win32_LogicalDiskToPartition" | ForEach-Object {
                            $ld = $_
                            [PSCustomObject]@{
                                driveName     = $ld.DeviceId # C:
                                IsSystemDrive = if ($p | Where-Object { $_.BootPartition }) { $true }else { $false }
                                freeSpace     = $ld.FreeSpace # in bytes
                                totalSpace    = $ld.Size # in bytes
                                fileSystem    = $ld.FileSystem # NTFS
                                physicalName  = $d.Name # \.PHYSICALDRIVE2
                                diskName      = $d.Caption # WDC WD5001AALS-xxxxxx
                                diskModel     = $d.Model # WDC WD5001AALS-xxxxxx
                                diskInterface = $d.InterfaceType # IDE
                                mediaStatus   = $d.Status # OK
                                volumeName    = $ld.VolumeName # System
                                volumeSerial  = $ld.VolumeSerialNumber # 12345678
                            }
                        }
                    }
                }
            }
        }
        else {
            Get-WmiObject -Query "select * from Win32_DiskDrive" | Where-Object { $_.Size } | ForEach-Object {
                $d = $_
                $d | ForEach-Object {
                    $Disk = $_
                    $p = Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='$($Disk.DeviceID)'}  WHERE AssocClass = Win32_DiskDriveToDiskPartition"
                    $p | ForEach-Object {
                        $Partition = $_
                        Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='$($Partition.DeviceID)'} WHERE AssocClass = Win32_LogicalDiskToPartition" | ForEach-Object {
                            $ld = $_
                            [PSCustomObject]@{
                                driveName     = $ld.DeviceId # C:
                                IsSystemDrive = if ($p | Where-Object { $_.BootPartition }) { $true }else { $false }
                                freeSpace     = $ld.FreeSpace # in bytes
                                totalSpace    = $ld.Size # in bytes
                                fileSystem    = $ld.FileSystem # NTFS
                                physicalName  = $d.Name # \.PHYSICALDRIVE2
                                diskName      = $d.Caption # WDC WD5001AALS-xxxxxx
                                diskModel     = $d.Model # WDC WD5001AALS-xxxxxx
                                diskInterface = $d.InterfaceType # IDE
                                mediaStatus   = $d.Status # OK
                                volumeName    = $ld.VolumeName # System
                                volumeSerial  = $ld.VolumeSerialNumber # 12345678
                            }
                        }
                    }
                }
            }
        }
    }
}
process {
    # Get values from parameters
    $Settings = [PSCustomObject]@{
        SystemDrive = [PSCustomObject]@{
            MinFreePercent = if ($env:SystemDriveMinFreePercent) { $env:SystemDriveMinFreePercent -replace '%' }else { $SystemDriveMinFreePercent }
            MinFreeBytes   = if ($env:SystemDriveMinFreeBytes) { Get-Size -Size $env:SystemDriveMinFreeBytes }else { $SystemDriveMinFreeBytes }
        }
        DataDrive   = [PSCustomObject]@{
            MinFreePercent = if ($env:DataDriveMinFreePercent) { $env:DataDriveMinFreePercent -replace '%' }else { $DataDriveMinFreePercent }
            MinFreeBytes   = if ($env:DataDriveMinFreeBytes) { Get-Size -Size $env:DataDriveMinFreeBytes }else { $DataDriveMinFreeBytes }
        }
    }
    # Get values from custom field
    if ($SystemDriveMinFreePercentCustomField) {
        $Settings.SystemDrive.MinFreePercent = Ninja-Property-Get -Name $SystemDriveMinFreePercentCustomField
    }
    if ($SystemDriveMinFreeBytesCustomField) {
        $Settings.SystemDrive.MinFreeBytes = Ninja-Property-Get -Name $SystemDriveMinFreeBytesCustomField
    }
    if ($DataDriveMinFreePercentCustomField) {
        $Settings.DataDrive.MinFreePercent = Ninja-Property-Get -Name $DataDriveMinFreePercentCustomField
    }
    if ($DataDriveMinFreeBytesCustomField) {
        $Settings.DataDrive.MinFreeBytes = Ninja-Property-Get -Name $DataDriveMinFreeBytesCustomField
    }
    if ($env:ExcludeDrives) {
        $ExcludeDrives = $env:ExcludeDrives
    }
    if ($ExcludeDrivesCustomField) {
        $ExcludeDrives = Ninja-Property-Get -Name $ExcludeDrivesCustomField
    }
    if ($env:ExcludeDrivesByName) {
        $ExcludeDrivesByName = $env:ExcludeDrivesByName
    }
    if ($env:ExcludeDrivesByNameCustomField) {
        $ExcludeDrivesByNameCustomField = $env:ExcludeDrivesByNameCustomField
    }

    # System.IO.DriveInfo is usable as far back as .NET 2.0 for Windows 7 compatibility.
    # Reference: https://learn.microsoft.com/en-us/dotnet/api/system.io.driveinfo?view=netstandard-2.0

    # Get drives that are in the ready state
    $Drives = Get-Drive

    $Results = if ($Drives) {
        $DrivesFiltered = if ($ExcludeDrivesByName) {
            $Drives | Where-Object { $_.volumeName -notlike "*$ExcludeDrivesByName*" }
        }
        else { $Drive }

        if ($ExcludeDrives) {
            $DriveAlerts = Invoke-DiskAlert -Drives $DrivesFiltered
            $DriveList = if ($ExcludeDrives -like "*,*") {
                $ExcludeDrives -split ',' | Sort-Object -Unique
            }
            else {
                $ExcludeDrives -split '' | Sort-Object -Unique | Select-Object -Skip 1
            }
            $DriveList | ForEach-Object {
                $Drive = $_
                $DriveAlerts | Where-Object { $_ -notlike "*$($Drive):*" }
            }
            
        }
        else {
            Invoke-DiskAlert -Drives $Drives $DrivesFiltered
        }
    }
    else {
        # Should never get here, how was the script executed?!
        "No drives found?!" | Out-String | Write-Host
        exit 2
    }

    if ($Results) {
        $Results | Out-String | Write-Host
        exit 1
    }
    else {
        Write-Host "No drives found with low free space."
        exit 0
    }
}
end {
    $ScriptVariables = @(
        [PSCustomObject]@{
            name           = "Exclude Drives"
            calculatedName = "excludedrives"
            required       = $false
            defaultValue   = $null
            valueType      = "TEXT"
            valueList      = $null
            description    = "List if mounted drives to exclude from low drive check. Example: CFZ or C,F,Z"
        }
        [PSCustomObject]@{
            name           = "Exclude Drives Custom Field"
            calculatedName = "excludedrivescustomfield"
            required       = $false
            defaultValue   = $null
            valueType      = "TEXT"
            valueList      = $null
            description    = "A custom field to get the value from. List if mounted drives to exclude from low drive check. Example: CFZ or C,F,Z"
        }
        [PSCustomObject]@{
            name           = "Exclude Drives By Name"
            calculatedName = "excludedrivesbyname"
            required       = $false
            defaultValue   = $null
            valueType      = "TEXT"
            valueList      = $null
            description    = "Exclude drives with with the specified text in it's name/label."
        }
        [PSCustomObject]@{
            name           = "Exclude Drives By Name Custom Field"
            calculatedName = "excludedrivesbynamecustomfield"
            required       = $false
            defaultValue   = $null
            valueType      = "TEXT"
            valueList      = $null
            description    = "A custom field to get the value from. Exclude drives with with the specified text in it's name/label."
        }
        [PSCustomObject]@{
            name           = "System Drive Minimum Size in Percent"
            calculatedName = "systemdriveminfreepercent"
            required       = $false
            defaultValue   = [PSCustomObject]@{
                type  = "TEXT"
                value = "10%"
            }
            valueType      = "TEXT"
            valueList      = $null
            description    = "The percentage of free space to alert on when the OS drive is below this percentage. Example: 50 or 50%"
        }
        [PSCustomObject]@{
            name           = "System Drive Minimum Size in Bytes"
            calculatedName = "systemdriveminfreebytes"
            required       = $false
            defaultValue   = [PSCustomObject]@{
                type  = "TEXT"
                value = "10GB"
            }
            valueType      = "TEXT"
            valueList      = $null
            description    = "The minimum free space to alert on when the OS drive is below this amount. Example: 50GB, 50000MB, or 53687091200"
        }
        [PSCustomObject]@{
            name           = "Data Drive Minimum Size in Percent"
            calculatedName = "datadriveminfreepercent"
            required       = $false
            defaultValue   = [PSCustomObject]@{
                type  = "TEXT"
                value = "20%"
            }
            valueType      = "TEXT"
            valueList      = $null
            description    = "The percentage of free space to alert on when a Data drive is below this percentage. Example: 50 or 50%"
        }
        [PSCustomObject]@{
            name           = "Data Drive Minimum Size in Bytes"
            calculatedName = "datadriveminfreebytes"
            required       = $false
            defaultValue   = [PSCustomObject]@{
                type  = "TEXT"
                value = "20GB"
            }
            valueType      = "TEXT"
            valueList      = $null
            description    = "The minimum free space to alert on when the Data drive is below this amount. Example: 50GB, 50000MB, or 53687091200"
        }
        [PSCustomObject]@{
            name           = "System Drive Minimum Size in Percent Custom Field"
            calculatedName = "systemdriveminfreepercentcustomfield"
            required       = $false
            defaultValue   = $null
            valueType      = "TEXT"
            valueList      = $null
            description    = "A custom field to get the value from. The percentage of free space to alert on when the OS drive is below this percentage. Example: 50 or 50%"
        }
        [PSCustomObject]@{
            name           = "System Drive Minimum Size in Bytes Custom Field"
            calculatedName = "systemdriveminfreebytescustomfield"
            required       = $false
            defaultValue   = $null
            valueType      = "TEXT"
            valueList      = $null
            description    = "A custom field to get the value from. The minimum free space to alert on when the OS drive is below this amount. Example: 50GB, 50000MB, or 53687091200"
        }
        [PSCustomObject]@{
            name           = "Data Drive Minimum Size in Percent Custom Field"
            calculatedName = "datadriveminfreepercentscustomfield"
            required       = $false
            defaultValue   = $null
            valueType      = "TEXT"
            valueList      = $null
            description    = "A custom field to get the value from. The percentage of free space to alert on when a Data drive is below this percentage. Example: 50 or 50%"
        }
        [PSCustomObject]@{
            name           = "Data Drive Minimum Size in Bytes Custom Field"
            calculatedName = "datadriveminfreebytescustomfield"
            required       = $false
            defaultValue   = $null
            valueType      = "TEXT"
            valueList      = $null
            description    = "A custom field to get the value from. The minimum free space to alert on when the Data drive is below this amount. Example: 50GB, 50000MB, or 53687091200"
        }
    )
    $ScriptName = "Condition Low Disk Space Alert"
}

Zugang zu über 700+ Skripten im NinjaOne Dojo Zugang erhalten

Wie das Skript Disk Space Monitor funktioniert

Das Skript sammelt zunächst Informationen über alle Laufwerke des Systems. Anschließend werden alle Laufwerke herausgefiltert, die Sie ausgeschlossen haben, und die verbleibenden Laufwerke mit den von Ihnen festgelegten Parametern verglichen. Wenn ein Laufwerk den angegebenen Mindestfreiraum unterschreitet, gibt das Skript eine Warnung aus, so dass Sie Maßnahmen ergreifen können, bevor es zu einem Problem wird. Eines der herausragenden Merkmale dieses Skripts ist seine Fähigkeit, Werte aus benutzerdefinierten Feldern zu ziehen. Das bedeutet, dass Sie Werte global oder von Rollen aus angeben können, was dem Skript eine weitere Ebene der Anpassung verleiht.

Umgestaltung der IT-Verwaltung mit NinjaOne

Es ist zwar möglich, den Festplattenspeicher ausschließlich mit PowerShell von einem lokalen Computer aus zu überwachen, aber es gibt eine noch bessere Möglichkeit, Ihre IT-Ressourcen aus der Ferne und in großem Umfang zu verwalten – NinjaOne. NinjaOne ist eine Unified-IT-Management-Plattform, die Abhilfemaßnahmen, ggf. unter Verwendung von Skripten, in hochflexible Geräterichtlinien integriert, die festlegen, wann Warnschwellenwerte erreicht werden und welche Maßnahmen daraufhin ergriffen werden sollten. NinjaOne bietet Zugang zu Hunderten von Skripten, die Ihnen nützlich sein können, und die Möglichkeit, eigene Skripte in fast jeder Skriptsprache zu erstellen. Mit NinjaOne können Sie alle Ihre IT-Endpunkte über ein einziges Dashboard in großem Umfang überwachen und verwalten. Mit Richtlinien und Skripten können Sie praktisch jede Routineaufgabe automatisieren, von der Installation von Software-Patches bis zur Erstellung von Berichten, und so Zeit sparen und Probleme proaktiv angehen, bevor sie zu Problemen werden.

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

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