Issues with a Task Sequence

Author: SCCMOG - Richie Schuster - SCCMOG.COM

Date: 05/01/2017

Name: Auto Snapshot VM before Patching

RunAs CMD: Powershell.exe -Executionpolicy Bypass -File PrePatchSnapShot.ps1

Description: This script has been created to auto snapshot a VM before patching by a task sequence from SCCM.

The script must be run as a Command Line in the task sequence by an account with access to VSphere.

Variables

$VMname = "$env:COMPUTERNAME" $VIserver = "tocvcenter01p.ion.media" $Username = "xxx" $Password = "xxx"

Create Credential to pass securely

$Cred = New-Object System.Management.Automation.PSCredential($Username, (ConvertTo-SecureString $Password -AsPlainText -Force))

Add the VMware snapin if not added

If ((Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null ) { Add-PSSnapin VMware.VimAutomation.Core }

Connect to tocvcenter01p.ion.media

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 }

Reset Connected Variable

$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 }

################################################################################################################
/r/SCCM Thread Parent