$VMname = "$env:COMPUTERNAME" $VIserver = "tocvcenter01p.ion.media" $Username = "xxx" $Password = "xxx"
$Cred = New-Object System.Management.Automation.PSCredential($Username, (ConvertTo-SecureString $Password -AsPlainText -Force))
If ((Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null ) { Add-PSSnapin VMware.VimAutomation.Core }
If ($global:DefaultVIServer -eq $null ) { Connect-VIServer -Server $VIserver #-Credential $Cred -Verbose } ElseIF ($global:DefaultVIServer -ne $VIserver ) { #Disconnect all server connections Disconnect-VIServer -Server $global:DefaultVIServers -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null #Re-connect to specific server Connect-VIServer -Server $VIserver }
$Connected = $global:DefaultVIServer.Name -eq $VIserver
If ($Connected -eq $true) {
#Snapshot Time
#Time Date for Snapshot name
$Date = Get-Date
$DateShort = $Date.ToShortDateString() -replace '[/]'
$TimeShort = $Date.ToShortTimeString()
$Snapshotname = "Before Patching $TimeShort $DateShort"
#Take Snapshot
New-Snapshot -VM $VMname -Name $Snapshotname -Description "This Snapshot was taken before patching the VM from the SCCM TaskSequence. $Date" -Verbose
#Check Snapshot complete
$SnapShots = Get-Snapshot -VM $VMname
$Taken = $Snapshots.Name.Contains($Snapshotname)
#If found Disconnect and Exit Script Success 0
If ($Taken -eq $true) {
Disconnect-VIServer -Server $VIserver -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
Exit 0
}
#If Failed Exit Script 999 Failing the Tasksequence
Else {
Exit 999
}
}
Elseif ($Connected -eq $false) { Exit 911 } Else { Exit 912 }