Skip to content

Instantly share code, notes, and snippets.

@sudo-battlekafer
Created March 3, 2022 22:22
Show Gist options
  • Save sudo-battlekafer/6cac03b7e9fea298603bb6c3735377ea to your computer and use it in GitHub Desktop.
Save sudo-battlekafer/6cac03b7e9fea298603bb6c3735377ea to your computer and use it in GitHub Desktop.
VMWare Snapshot creation script
param(
[parameter(mandatory = $true)][String]$VMName
)
# Requires that you have PowerCli installed
# Get it with the command: PS> Install-Module -Name VMware.PowerCLI
Clear-Host
Write-Verbose -Message "Loading Modules..." -Verbose
if (Get-Module -ListAvailable -Name VMware.PowerCLI) {
Write-Host "Module exists"
}
else {
Write-Host @"Powershell Module Needs to be installed
Run the command with 'Install-Module -Name VMware.PowerCLI' and try again"@
Exit
}
Get-Module -ListAvailable *VMware* | Import-Module | Out-Null
# connect to VCenter
# Requires that you have a file in your username's .ssh folder call 'vmca.xml'
$path = "C:\Users\$env:UserName\.ssh\vmca.xml"
if(![System.IO.File]::Exists($path)){
Write-Host @"Credential file not found. Create one with the command:
New-VICredentialStoreItem -Host <vcenter fqdn or IP> -User <USERNAME> -Password <PASSWORD> -File C:\Users\<USERNAME>\.ssh\vmca.xml
Example: New-VICredentialStoreItem -host vcenter.vmware.com -User jsmith -Password 12345678901234 -File C:\Users\jsmith\.ssh\vmca.xml"@
Exit
}
$credentials = Get-VICredentialStoreItem -file $path
Write-Host "Connecting to VCenter"
connect-viserver $credentials.Host -User $credentials.User -Password $credentials.Password
#list current snapshots
Get-VM -Name $VMName | Get-Snapshot
#clean old snapshots
Get-VM -Name $VMName | Get-Snapshot | Where {$_.Created -lt (Get-Date).AddDays(-15)} | Remove-Snapshot
#create new
New-Snapshot -VM $VMName -Name "$(get-date -f yyyy-MM-dd)-Snapshot"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment