## TO-DO:  update SQL status to Expired-Alerted when a ticket is created, so duplicate tickets are not generated

[CmdletBinding()]
param (
    [string]
    $VMName,
    
    [int]
    $Id,  # ??

    [switch]
    $WhatIf
)

Write-Verbose -Message "Connect to vCenter and ServiceNow"
New-ITDServiceNowSession -Environment Production -Credential $Secret:SnowVMCred
Connect-ITDvCenter -Credential $Secret:svcitdiaasauto

# find all VMs, with VMName if entered
If ($PSBoundParameters.ContainsKey('VMName')) {
    Write-Verbose -Message "VMname parameter found $VMName" -Verbose
    $VMs = Get-VM -Name $VMName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
}
Else {
    Write-Verbose -Message "VMname parameter not found" -Verbose
    $VMs = Get-VM | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
}

# find expired snapshots of the VMs
If ($PSBoundParameters.ContainsKey('Id')) {

    Write-Verbose -Message "ID parameter found $Id" -Verbose
    $AllSnapshots = $VMs | Get-Snapshot | Where-Object Name -Like "AutoSnap_$Id*"
}
Else {
    Write-Verbose -Message "ID parameter not found" -Verbose
    $AllSnapshots = $VMs | Get-Snapshot | Where-Object Name -Like "AutoSnap_*"
}

ForEach ($Snapshot in $AllSnapshots) {
    $SnapshotObj = $Snapshot.Description | ConvertFrom-Json
    If ( $SnapshotObj.Expire -lt (Get-Date).AddHours(-24) ) {
        $NewITDServiceNowIncidentParams = @{
            CallerUsername = 'svcvmwareadm';
            ShortDescription = ("VMware Snapshot #" + $SnapshotObj.Id + " cleanup failure.");
            Description = ("VMware Snapshot #" + $SnapshotObj.ID + " cleanup failure.  Snapshot expired more than 24 hours ago, but it still exists.");
            Impact = 3;
            Urgency = 3;
            Category = 'Systems Platforms - Systems';
            Subcategory = 'VMware';
            AssignmentGroup = 'NDIT-Computer Systems Windows';
        }
        New-ITDServiceNowIncident @NewITDServiceNowIncidentParams
    }
}



Disconnect-ITDvCenter