This commit is contained in:
Zack Meier
2026-04-15 15:45:50 -05:00
commit 1d304511b8
613 changed files with 140998 additions and 0 deletions
@@ -0,0 +1,49 @@
trigger:
- main
name: 'ITD.Infra-VMware.Snapshot'
variables:
major: 0
minor: 1
patch: $(Build.BuildID)
buildVer: $(major).$(minor).$(Build.BuildID)
pool: itdwinautop1
stages:
- stage: Build
jobs:
- job: Build
steps:
- task: PowerShell@2
inputs:
filePath: '$(System.DefaultWorkingDirectory)/Build/build.ps1'
- task: NuGetCommand@2
inputs:
command: 'pack'
packagesToPack: '$(System.DefaultWorkingDirectory)/ITD.Infra-VMware.Snapshot.nuspec'
versioningScheme: byEnvVar
versionEnvVar: buildVer
buildProperties: 'VERSIONHERE=$(buildVer)'
- task: PublishBuildArtifacts@1
inputs:
PathtoPublish: '$(Build.ArtifactStagingDirectory)'
ArtifactName: 'NuGetPackage'
publishLocation: 'Container'
- stage: Deploy
jobs:
- job: Deploy
steps:
- task: DownloadPipelineArtifact@2
inputs:
buildType: 'current'
artifactName: 'NuGetPackage'
itemPattern: '**'
targetPath: '$(Pipeline.Workspace)'
- task: NuGetCommand@2
inputs:
command: 'push'
packagesToPush: '$(Pipeline.Workspace)/ITD.Infra-VMware.Snapshot.$(major).$(minor).$(Build.BuildID).nupkg'
nuGetFeedType: external
publishFeedCredentials: 'ITD_PwshGallery'
@@ -0,0 +1,17 @@
$buildVersion = $env:BUILDVER
$moduleName = 'ITD.Infra-VMware.Snapshot'
$manifestPath = Join-Path -Path $env:SYSTEM_DEFAULTWORKINGDIRECTORY -ChildPath "$moduleName.psd1"
$modulePath = Join-Path -Path $env:SYSTEM_DEFAULTWORKINGDIRECTORY -ChildPath "$moduleName.psm1"
## Update build version in manifest
$manifestContent = Get-Content -Path $manifestPath -Raw
$manifestContent = $manifestContent -replace '<ModuleVersion>', $buildVersion
## Update functions to export in manifest
Import-Module $modulePath
$funcStrings = (Get-Module ITD.Infra-VMware.Snapshot).ExportedCommands.Values.Name
$funcStrings = "'$($funcStrings -join "','")'"
$manifestContent = $manifestContent -replace "<FunctionsToExport>", $funcStrings
$manifestContent | Set-Content -Path $manifestPath
@@ -0,0 +1,12 @@
<?xml version="1.0"?>
<package>
<metadata>
<id>ITD.Infra-VMware.Snapshot</id>
<version>$VERSIONHERE$</version>
<authors>Zack Meier</authors>
<description>Functions for VMware Snapshot tasks</description>
</metadata>
<files>
<file src="**" exclude="**\.git\**;**\Build\**" />
</files>
</package>
@@ -0,0 +1,133 @@
#
# Module manifest for module 'ITD.Infra-VMware.Snapshot'
#
# Generated by: zmeier
#
# Generated on: 5/19/2022
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'ITD.Infra-VMware.Snapshot.psm1'
# Version number of this module.
ModuleVersion = '<ModuleVersion>'
# Supported PSEditions
CompatiblePSEditions = 'Desktop', 'Core'
# ID used to uniquely identify this module
GUID = 'b45cb1f1-f08c-4873-948b-232e3ce26418'
# Author of this module
Author = 'zmeier'
# Company or vendor of this module
CompanyName = 'Unknown'
# Copyright statement for this module
Copyright = '(c) zmeier. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Functions for VMware Virtual Machine tasks'
# Minimum version of the PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# ClrVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @(<FunctionsToExport>)
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
# Prerelease string of this module
# Prerelease = ''
# Flag to indicate whether the module requires explicit user acceptance for install/update/save
# RequireLicenseAcceptance = $false
# External dependent modules of this module
ExternalModuleDependencies = @("ITD.Infra-Passwordstate","ITD.Infra-Networking-Infoblox","ITD.Shared-ServiceNow","ITD.Infra-VMware.VirtualMachine","ITD.Infra-VMware.Administration")
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
@@ -0,0 +1,23 @@
#Get public and private function definition files.
$Public = @( Get-ChildItem -Path $PSScriptRoot\Public\*.ps1 -ErrorAction SilentlyContinue )
$Private = @( Get-ChildItem -Path $PSScriptRoot\Private\*.ps1 -ErrorAction SilentlyContinue )
#Dot source the files
Foreach($import in @($Public + $Private))
{
Try
{
. $import.fullname
}
Catch
{
Write-Error -Message "Failed to import function $($import.fullname): $_"
}
}
# Here I might...
# Read in or create an initial config file and variable
# Export Public functions ($Public.BaseName) for WIP modules
# Set variables visible to the module and its functions only
Export-ModuleMember -Function $Public.Basename
@@ -0,0 +1,143 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
A longer description of the function, its purpose, common use cases, etc.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function New-ITDVMwareVMSnapshotTaskV3 {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]
$VMName,
[Parameter(Mandatory = $true)]
[string]
$Name,
[string]
$Description,
[datetime]
$DateTime,
[string[]]
$Email
)
begin {
}
process {
Write-Verbose -Message "Start Loop"
ForEach ($VName in $VMName) {
Write-Verbose -Message "Start $VMName"
$VM = $null
$VM = Get-VM -Name $VMName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" } -ErrorAction SilentlyContinue
If ($VM) {
$ViServer = $VM.Uid.split('@')[1].split(':')[0]
$NewSnapshotParams = @{
Name = $Name;
RunAsync = $true;
}
switch ($PSBoundParameters.Keys) {
Description {
$NewSnapshotParams.Description = $Description
}
Memory {
$NewSnapshotParams.Memory = $Memory;
$NewSnapshotParams.RunAsync = $false;
}
}
Write-Verbose -Message ("Validate DateTime is in the future")
If ($DateTime -lt (Get-Date)) {
Write-Warning -Message "DateTime is in the past, recursively running the function again, adjusting start time to 60 seconds from now."
$NewITDVMwareVMSnapshotTaskParams = @{
VMName = $VMName;
Name = $Name;
Description = $Description;
DateTime = (Get-Date).AddSeconds(60);
Email = ($Email -join ',');
}
New-ITDVMwareVMSnapshotTaskV3 @NewITDVMwareVMSnapshotTaskParams
}
else {
Write-Verbose -Message ("Attempt sched task creation")
try {
$si = Get-View ServiceInstance -Server $VIServer
$scheduledTaskManager = Get-View $si.Content.ScheduledTaskManager -Server $VIServer
$spec = New-Object VMware.Vim.ScheduledTaskSpec
$spec.Name = $Name, $VName -join '_'
$spec.Description = "$Description"
$spec.Enabled = $true
switch ($PSBoundParameters.Keys) {
Email {
$spec.Notification = $Email
}
}
$spec.Scheduler = New-Object VMware.Vim.OnceTaskScheduler
$spec.Scheduler.runat = $DateTime
$spec.Action = New-Object VMware.Vim.MethodAction
$spec.Action.Name = "CreateSnapshot_Task"
$Memory = $false
$Quiesce = $false
@($Name, $Description, $Memory, $Quiesce) | ForEach-Object {
$arg = New-Object VMware.Vim.MethodActionArgument
$arg.Value = $_
$spec.Action.Argument += $arg
}
Start-Sleep -Seconds 20
try {
$scheduledTaskManager.CreateObjectScheduledTask($vm.ExtensionData.MoRef, $spec)
}
catch [System.Management.Automation.MethodInvocationException] {
Write-Warning -Message "System.Management.Automation.MethodInvocationException"
If ($error[0].Exception.Message -like "*You have attempted to schedule the scheduler at a time value*" -and $error[0].Exception.Message -Like "* in the past,*") {
Write-Warning -Message "DateTime is in the past, recursively running the function again, adjusting start time to 60 seconds in the future from now."
$NewITDVMwareVMSnapshotTaskParams = @{
VMName = $VMName;
Name = $Name;
Description = $Description;
DateTime = (Get-Date).AddSeconds(60);
Email = $Email;
}
New-ITDVMwareVMSnapshotTaskV3 @NewITDVMwareVMSnapshotTaskParams
}
}
catch {
Write-Warning -Message "Default"
}
}
catch {
Write-Error $error[0]
}
}
}
}
}
end {
}
}
@@ -0,0 +1,61 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
Create a new snapshot of a VMware Virtual Machine
.NOTES
Create a new snapshot of a VMware Virtual Machine
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
New-ITDVMwareVMSnapshot -VMName itdwinautot1.nd.gov -Name "Before Upgrade to 7.0U3k" -Description "Before Upgrade, delete after 3/3/2023"
#>
function New-ITDVMwareVMSnapshotV3 {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]
$VMName,
[Parameter(Mandatory = $true)]
[string]
$Name,
[string]
$Description,
[switch]
$Memory
)
begin {
}
process {
ForEach ($VName in $VMName) {
$VM = Get-VM -Name $VName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
$NewSnapshotParams = @{
Name = $Name;
RunAsync = $true;
}
switch ($PSBoundParameters.Keys) {
Description {
$NewSnapshotParams.Description = $Description
}
Memory {
$NewSnapshotParams.Memory = $Memory;
$NewSnapshotParams.RunAsync = $false;
}
}
$NewSnapshotParams
$VM | New-Snapshot @NewSnapshotParams
}
}
end {
}
}
@@ -0,0 +1,58 @@
<#
.SYNOPSIS
This function for cleanup of AutoSnap* scheduled tasks that have completed their lifecycle.
.DESCRIPTION
This function for cleanup of vCenter scheduled tasks named AutoSnap*, all of which have completed their lifecycle.
.NOTES
Information or caveats about the function e.g. 'This function is not supported in Linux'
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
Test-MyTestFunction -Verbose
Explanation of the function or its result. You can include multiple examples with additional .EXAMPLE lines
#>
function Remove-ITDVMwareVMSnapshotTaskExpired {
[CmdletBinding()]
param (
[switch]
$WhatIf
)
begin {
}
process {
Write-Verbose -Message ("Gathering all scheduled tasks with AutoSnap in the task name, this will take some time")
$si = Get-View ServiceInstance
$scheduledTaskManager = Get-View $Si.Content.ScheduledTaskManager
$AllScheduledTasks = Get-View -Id $scheduledTaskManager.ScheduledTask | Where-Object { $_.Info.Name -like "AutoSnap*" } | Select-Object -Unique
ForEach ($ScheduledTask in $AllScheduledTasks) {
Write-Verbose -Message ("Start " + $ScheduledTask.Info.Name)
If ($ScheduledTask.Info.Name -like "AutoSnap*") {
# Double check snapshot task
If ($ScheduledTask.Info.PrevRunTime -lt (Get-Date) -and $ScheduledTask.Info.NextRunTime -eq $null) {
# if run once and completed
If ($WhatIf){
Write-Host -Message ("What if: Performing the operation RemoveScheduledTask() on target " + $ScheduledTask.Info.Name)
} Else {
Write-Verbose -Message ("Removing scheduled task named " + $ScheduledTask.Info.Name)
$ScheduledTask.RemoveScheduledTask()
}
}
}
Else {
# do nothing
}
}
}
end {
}
}
@@ -0,0 +1,42 @@
<#
.SYNOPSIS
A short one-line action-based description, e.g. 'Tests if a function is valid'
.DESCRIPTION
Create a new snapshot of a VMware Virtual Machine
.NOTES
Create a new snapshot of a VMware Virtual Machine
.LINK
Specify a URI to a help page, this will show when Get-Help -Online is used.
.EXAMPLE
New-ITDVMwareVMSnapshot -ComputerName itdwinautot1.nd.gov -Name "Before Upgrade to 7.0U3k" -Description "Before Upgrade, delete after 3/3/2023"
#>
function Remove-ITDVMwareVMSnapshotV3 {
[CmdletBinding()]
param (
[string]
$ComputerName,
[string]
$Name
)
begin {
}
process {
$VM = Get-VM -Name $ComputerName | Where-Object { $_.ExtensionData.summary.config.ManagedBy.Type -ne "placeholderVm" }
$GetSnapshotParams = @{
Name = $Name
}
$VM | Get-Snapshot @GetSnapshotParams | Remove-Snapshot -Confirm:$false
}
end {
}
}
@@ -0,0 +1,20 @@
# Introduction
TODO: Give a short introduction of your project. Let this section explain the objectives or the motivation behind this project.
# Getting Started
TODO: Guide users through getting your code up and running on their own system. In this section you can talk about:
1. Installation process
2. Software dependencies
3. Latest releases
4. API references
# Build and Test
TODO: Describe and show how to build your code and run the tests.
# Contribute
TODO: Explain how other users and developers can contribute to make your code better.
If you want to learn more about creating good readme files then refer the following [guidelines](https://docs.microsoft.com/en-us/azure/devops/repos/git/create-a-readme?view=azure-devops). You can also seek inspiration from the below readme files:
- [ASP.NET Core](https://github.com/aspnet/Home)
- [Visual Studio Code](https://github.com/Microsoft/vscode)
- [Chakra Core](https://github.com/Microsoft/ChakraCore)
@@ -0,0 +1,37 @@
CREATE TABLE Infra_VMware_VirtualMachine_VMSnapshots_NPD (
ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
VMName varchar(255) NOT NULL,
DateTime DateTime NOT NULL,
RequestedBy varchar(255) NOT NULL,
DurationHours int NOT NULL,
Status varchar(255) NOT NULL,
NotifyEmail varchar(255),
TakenDateTime DateTime,
ExpireDateTime DateTime,
DeleteDateTime DateTime,
PSUJobIdRequest int,
PSUJobIdSchedule int,
PSUJobIdDelete int
)
CREATE TABLE Infra_VMware_VirtualMachine_VMSnapshots_PRD (
ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
VMName varchar(255) NOT NULL,
DateTime DateTime NOT NULL,
RequestedBy varchar(255) NOT NULL,
DurationHours int NOT NULL,
Status varchar(255) NOT NULL,
NotifyEmail varchar(255),
TakenDateTime DateTime,
ExpireDateTime DateTime,
DeleteDateTime DateTime
)
ALTER TABLE Infra_VMware_VirtualMachine_VMSnapshots_PRD
DROP COLUMN PSUJobId
ALTER TABLE Infra_VMware_VirtualMachine_VMSnapshots_PRD
ADD PSUJobIdSchedulet int
ALTER TABLE Infra_VMware_VirtualMachine_VMSnapshots_PRD
ADD PSUJobIdDelete int
@@ -0,0 +1,23 @@
New-UDApp -Title 'NewITDVMwareVMSnapshotTask' -Pages @(
New-UDPage -Name "NewITDVMwareVMSnapshotTask" -Content {
New-UDForm -Content {
New-UDTextbox -Label 'VMName' -Id 'VMName'
New-UDTextbox -Label 'HoursToKeep' -Id 'HoursToKeep'
New-UDDatePicker -Label 'StartDate' -Id "StartDate" -Variant dialog
New-UDTimePicker -Label 'StartTime' -Id "StartTime"
} -OnSubmit {
#Show-UDToast -Message $EventData.txtTextField
#Show-UDToast -Message $EventData.chkCheckbox
#Invoke-PSUScript -Script 'Test-FormSubmission.ps1' -VMName $EventData.VMName
#"Current User = $User, StartDate = " + $EventData.StartDate + " " + $EventData.StartTime
$StartDateTime = $EventData.StartDate.Date
$StartDateTime = $StartDateTime.AddHours($EventData.StartTime.Hour)
$StartDateTime = $StartDateTime.AddMinutes($EventData.StartTime.Minute)
Show-UDToast -Message ("Start Date/Time is: " + $StartDateTime) -Duration 20000
}
}
)