Create a linked clone from a parent vm using vmware sdk

I was working on a project to create a 90 day eval machine that used linked clones.  This article isn’t meant to educate on Linked clones although it’s a great concept to have a Parent VM and another disk that contains just changes.  The benefits saves a lot of space in storage.   

Text only version of script
http://iislogs.com/ss/linkedclone.txt

Here is a couple articles to check on linked clones

Here is the script

param(
    [string]$ParentVMName = “UP1″,
    [string]$vCenterHostName = “vCenterSS”,
    [string]$vCenterUserName= “domain\user”,
    [string]$vCenterUserPassword= “UP2″,
    [string]$cloneName = “UP3″,
    [string]$OSType = “Windows”,
    [string]$TimeZone = “035”,
    [string]$DHCPPortGroup = “123456”,
    [string]$Domain = “example.com”,
    [string]$DomainUserName = “user@example.com”,
    [string]$DomainPassword = “UP4″,
    [string]$AdminPassword = “changeme”,
    [string]$FullName = “CompanyA”,
    [string]$OrgName = “Example, Inc”,
    [string]$CustomizeTemplate1 = “$($cloneName)-Temp1″,
    [string]$CustomizeTemplate2 = “$($cloneName)-Temp2″,
    [string]$ServerDescription = “UP5″,
    [string]$PrimaryDNSSuffix = “example.com”,
    #This is a enum VM, PREFIX CUSTOM
    [string]$NamingScheme=”VM”
    )

function LoadSnapin{
  param($PSSnapinName)
  if (!(Get-PSSnapin | where {$_.Name -eq $PSSnapinName})){
    Add-pssnapin -name $PSSnapinName
  }
}
LoadSnapin -PSSnapinName   “VMware.VimAutomation.Core”

#Better to pass in an array and randomly select datastore
function GetDataStore
{
    $value = (Get-Random) %3
    switch ($value)
    {
        0 {    return “datastore1″    }
        1 {    return “datastore2″    }
        2 {    return “datastore3″    }
        default {return “datastore1″}
    }
}   

# Constants for status
$STATUS_VM_NOT_STARTED = “VmNotStarted”
$STATUS_CUSTOMIZATION_NOT_STARTED = “CustomizationNotStarted”
$STATUS_STARTED = “CustomizationStarted”
$STATUS_SUCCEEDED = “CustomizationSucceeded”
$STATUS_FAILED = “CustomizationFailed”
$STATUS_NOT_COMPLETED_LIST = @( $STATUS_CUSTOMIZATION_NOT_STARTED, $STATUS_STARTED )
# constants for event types     
$EVENT_TYPE_CUSTOMIZATION_STARTED = “VMware.Vim.CustomizationStartedEvent”
$EVENT_TYPE_CUSTOMIZATION_SUCCEEDED = “VMware.Vim.CustomizationSucceeded”
$EVENT_TYPE_CUSTOMIZATION_FAILED = “VMware.Vim.CustomizationFailed”
$EVENT_TYPE_VM_START = “VMware.Vim.VmStartingEvent”
# seconds to sleep before next loop iteration
$WAIT_INTERVAL_SECONDS = 15
[int] $timeoutSeconds = 1200

function GetOSCustomizationSpecStatus($vm, $timeoutSeconds)
{
   # the moment in which the script has started
   # the maximum time to wait is measured from this moment
   $startTime = Get-Date
   # we will check for “start vm” events 5 minutes before current moment
   $startTimeEventFilter = $startTime.AddMinutes(-5)
   # initializing list of helper objects
   # each object holds VM, customization status and the last VmStarting event
   $vmDescriptors = New-Object System.Collections.ArrayList

   Write-Host “Start monitoring customization process for vm ‘$vm'”
   $obj = “” | select VM,CustomizationStatus,StartVMEvent
   $obj.VM = $vm
   # getting all events for the $vm,
   #  filter them by type,
   #  sort them by CreatedTime,
   #  get the last one
   $obj.StartVMEvent = Get-VIEvent -Entity $vm -Start $startTimeEventFilter | where { $_ -is $EVENT_TYPE_VM_START } | Sort CreatedTime | Select -Last 1
    if (-not $obj.StartVMEvent)
    {
        $obj.CustomizationStatus = $STATUS_VM_NOT_STARTED
    } else
    {
        $obj.CustomizationStatus = $STATUS_CUSTOMIZATION_NOT_STARTED
    }
    [void]($vmDescriptors.Add($obj))
   # declaring script block which will evaluate whether
   # to continue waiting for customization status update
   $shouldContinue = {
      # is there more virtual machines to wait for customization status update
      # we should wait for VMs with status $STATUS_STARTED or $STATUS_CUSTOMIZATION_NOT_STARTED
      $notCompletedVms = $vmDescriptors | where { $STATUS_NOT_COMPLETED_LIST -contains $_.CustomizationStatus }
      # evaluating the time that has elapsed since the script is running
      $currentTime = Get-Date
      $timeElapsed = $currentTime – $startTime
      $timoutNotElapsed = ($timeElapsed.TotalSeconds -lt $timeoutSeconds)
      # returns $true if there are more virtual machines to monitor
      # and the timeout is not elapsed
      return ( ($notCompletedVms -ne $null) -and ($timoutNotElapsed) )
   }
   while (& $shouldContinue)
   {
      foreach ($vmItem in $vmDescriptors)
      {
         $vmName = $vmItem.VM.Name
         switch ($vmItem.CustomizationStatus)
         {
            $STATUS_CUSTOMIZATION_NOT_STARTED
            {
               # we should check for customization started event
               $vmEvents = Get-VIEvent -Entity $vmItem.VM -Start $vmItem.StartVMEvent.CreatedTime
               $startEvent = $vmEvents | where { $_ -is $EVENT_TYPE_CUSTOMIZATION_STARTED }
               if ($startEvent) {
                  $vmItem.CustomizationStatus = $STATUS_STARTED
                  Write-Host “Customization for VM ‘$($vm)’ has started”
               }
               break;
            }
            $STATUS_STARTED
            {
               # we should check for customization succeeded or failed event
               $vmEvents = Get-VIEvent -Entity $vmItem.VM -Start $vmItem.StartVMEvent.CreatedTime
               $succeedEvent = $vmEvents | where { $_ -is $EVENT_TYPE_CUSTOMIZATION_SUCCEEDED }
               $failedEvent = $vmEvents | where { $_ -is $EVENT_TYPE_CUSTOMIZATION_FAILED }
               if ($succeedEvent)
               {
                  $vmItem.CustomizationStatus = $STATUS_SUCCEEDED
                  Write-Host “Customization for VM ‘$($vm)’ has successfully completed”
               }
               if ($failedEvent)
               {
                  $vmItem.CustomizationStatus = $STATUS_FAILED
                  Write-Host “Customization for VM ‘$($vm)’ has failed”
               }
               break;
            }
            default
            {
               # in all other cases there is nothing to do
               #    $STATUS_VM_NOT_STARTED -> if VM is not started, there’s no point to look for customization events
               #    $STATUS_SUCCEEDED -> customization is already succeeded
               #    $STATUS_FAILED -> customization
               break;
            }
         } # end of switch
      } # end of the foreach loop
      Write-Host “Sleeping for $WAIT_INTERVAL_SECONDS seconds”
      Sleep $WAIT_INTERVAL_SECONDS
   } # end of while loop
   # preparing result, without the helper column StartVMEvent
   $result = $vmDescriptors | select VM,CustomizationStatus
   Write-Host “I’m here $result[1]”

   if($result[1] -ne “CustomizationSucceeded”)
   {
    write-host “Waiting for VM Tools to Start”
<#
    do {

    $toolsStatus = (Get-VM $cloneName).extensiondata.Guest.ToolsStatus

    write-host $toolsStatus

    start-sleep -s 5

    } until ( $toolsStatus -eq ‘toolsOk’ )
#>
    Write-Host “Tools are running”

    $InvokeAdminPassword = ConvertTo-SecureString -String $AdminPassword -asplaintext -force
    $cmdAddToDomain = “netdom join /d:$($Domain) $cloneName /ud:$($DomainUserName) /pd:$($DomainPassword) /reboot:30″
    If ($ParentVMName -match ‘DEV1′ )
        {
            $varAddToDomain = Invoke-VMScript -VM $cloneName -ScriptText $cmdAddToDomain -GuestUser “DevAdmin1″ -GuestPassword $InvokeAdminPassword
        }
    Else
        {
            $varAddToDomain = Invoke-VMScript -VM $cloneName -ScriptText $cmdAddToDomain -GuestUser “Admin1″ -GuestPassword $InvokeAdminPassword
        }
    $varAddToDomain = Invoke-VMScript -VM $cloneName -ScriptText $cmdAddToDomain -GuestUser “Admin1″ -GuestPassword $InvokeAdminPassword
    Write-Host $varAddToDomain
   }
   return $result
}

function AddToDomain
{
    write-host “Waiting for VM Tools to Start”

<#    do {

    $toolsStatus = (Get-VM $cloneName).extensiondata.Guest.ToolsStatus

    write-host $toolsStatus

    start-sleep -s 5

    } until ( $toolsStatus -eq ‘toolsOk’ )
#>
    Write-Host “Tools are running”

    Write-Host “Add to Domain using Netdom”
    $InvokeAdminPassword = ConvertTo-SecureString -String $AdminPassword -asplaintext -force
    $cmd = “netdom join /d:$($Domain) $cloneName /ud:$($DomainUserName) /pd:$($DomainPassword) /reboot:30″
        If ($ParentVMName -match ‘Dev1′ )
        {
            $netDomOutPut = Invoke-VMScript -VM $cloneName -ScriptText $cmd -GuestUser “DevAdmin1″ -GuestPassword $InvokeAdminPassword
        }
        Else
        {
            $netDomOutPut = Invoke-VMScript -VM $cloneName -ScriptText $cmd -GuestUser “Admin1″ -GuestPassword $InvokeAdminPassword
        }
    $netDomOutPut = Invoke-VMScript -VM $cloneName -ScriptText $cmd -GuestUser “Admin1″ -GuestPassword $InvokeAdminPassword
    $date = Get-Date -Format MM-dd-yy

    #Adding output of netdom for Scorch to consume
    Add-Content -path “F:\Logs\NetDomOutput\$($cloneName)-$($date).txt” -value $netDomOutPut -force
    ipconfig /registerdns
}

Connect-VIServer -Server $vCenterHostName -User $vCenterUserName -Password $vCenterUserPassword

    #Creates the VM
    $sourceVM = Get-VM $ParentVMName | Get-View
    $cloneFolder = $sourceVM.parent
    $cloneSpec = new-object Vmware.Vim.VirtualMachineCloneSpec
    $cloneSpec.Snapshot = $sourceVM.Snapshot.CurrentSnapshot
    $cloneSpec.Location = new-object Vmware.Vim.VirtualMachineRelocateSpec

    #Creates Linked clone
    $cloneSpec.Location.DiskMoveType = [Vmware.Vim.VirtualMachineRelocateDiskMoveOptions]::createNewChildDiskBacking

    #Defines the Datastore, calls a function to get a specific datastore
    $Datastore = GetDataStore
    $cloneSpec.Location.Datastore = (Get-View -ViewType Datastore -Property Name -Filter @{“Name”=$DataStore}).MoRef
    $sourceVM.CloneVM_Task( $cloneFolder, $cloneName, $cloneSpec )

    $Spec1 = New-OSCustomizationSpec -FullName $FullName -OrgName $OrgName -OSType $OSType -ChangeSID -Name $CustomizeTemplate1 -Type NonPersistent -WorkGroup WK -AdminPassword $AdminPassword -TimeZone $TimeZone -Description $ServerDescription -LicenseMode PerSeat -DnsSuffix $PrimaryDNSSuffix
    Start-Sleep -s 4
    $Spec1 = Get-OSCustomizationSpec $CustomizeTemplate1
    Start-Sleep -s 4

    Get-VM $cloneName | Set-VM -OSCustomizationSpec $Spec1 -Confirm:$false -Description $ServerDescription | Start-VM
    $NIC = Get-NetworkAdapter -VM $cloneName
    Set-NetworkAdapter -NetworkAdapter $NIC -Connected $false -StartConnected $false -Confirm:$false
    Start-Sleep -s 4

    GetOSCustomizationSpecStatus -Vm $cloneName -timeoutSeconds 1200

    $a = Get-VM -Name $cloneName
    Stop-VM -VM $a -confirm:0

    Start-Sleep -m 250

    while ($a.PowerState -eq “PoweredOn”)
    {   
        Write-Host “Sleeping for 5 seconds”
        $a = get-vm -Name $cloneName
        start-sleep -s 5
    }

    Get-VM $cloneName  | Start-VM
    Start-Sleep 30
    $NIC = Get-NetworkAdapter -VM $cloneName
    Set-NetworkAdapter -NetworkAdapter $NIC -NetworkName $DHCPPortGroup -Connected $true -StartConnected $true -Confirm:$false
    Start-Sleep 30

    #GetOSCustomizationSpecStatus -Vm $cloneName -timeoutSeconds 1200
    AddToDomain
    Remove-OSCustomizationSpec -OSCustomizationSpec $Spec1 -Confirm:$false

Disconnect-VIServer -Server $vCenterHostName -Confirm:$false | out-null

process files with .TMP file extensions

We received a question how to process with .TMP file extensions.  IISLogs has a feature called Per Directory that was introduced in 2.0.  The feature allows an administrator to have granular control on a per directory basis.  We added the .TMP extension as an option in the Per Directory feature, please review the Per Directory article for complete options.  If you have any questions, feel free to contact our support alias @ info@iislogs.com

Open IISLogsGUI, Select Per Directory option

Fill in the Directory Name and other attributes you need.

Select TMP

Capture

When you save this, in the install folder the data is stored in a file called IISLogsPerDirectory.xml

<?xml version=”1.0″ standalone=”yes”?>
<NewDataSet>
  <Table1>
    <DirectoryName>c:\inetpub\temp\test\</DirectoryName>
    <ZipFile>false</ZipFile>
    <ZipRetentionPeriod>0</ZipRetentionPeriod>
    <DeleteOriginalFile>false</DeleteOriginalFile>
    <DeleteFile>true</DeleteFile>
    <DeleteRetentionPeriod>48</DeleteRetentionPeriod>
    <Recursive>false</Recursive>
    <ProcessRootFolderRecursive>false</ProcessRootFolderRecursive>
    <ZipFilePath>local</ZipFilePath>
    <IncludeComputerName>false</IncludeComputerName>
    <ProcessUnknownExtensions>false</ProcessUnknownExtensions>
    <ProcessTXT>false</ProcessTXT>
    <ProcessBAK>false</ProcessBAK>
    <ProcessDAT>false</ProcessDAT>
    <ProcessXML>false</ProcessXML>
    <NamingConvention>Default</NamingConvention>
    <Delimiter>!</Delimiter>
    <ProcessEXE>false</ProcessEXE>
    <ProcessMSP>false</ProcessMSP>
    <ProcessDLL>false</ProcessDLL>
    <ProcessINI>false</ProcessINI>
    <ProcessCFG>false</ProcessCFG>
    <ProcessTMP>true</ProcessTMP>
    <LogsDWM>1</LogsDWM>
    <PreserveDirPath>true</PreserveDirPath>
  </Table1>
</NewDataSet>

Cheers,

Steve Schofield
Microsoft MVP – IIS

The application has failed to start because its side-by-side configuration is incorrect error in IISLogs

We have an occasional support question a person receives an error when trying to execute IISLogs.

Problem:
The problem is a space “&nbsp;” or “&#x0;!” stored within the configuration item normally causes the issue.

<add key=”MonitoredEntireDirectories” value=”&nbsp;” />

or

<add key=”MonitoredEntireDirectories” value=”&#x0;!” />

Solution:

Remove the “&nbsp;” or “&#x0!” value using a text editor such as Notepad.

side-by-side-error3

Here are screenshots to showing the error and where to look.

side-by-side-error1

side-by-side-error2

Ping Sweep test using PowerCLI and vCenter

I had a reason to do a ping sweep across a set of machines with vCenter using PowerCLI.  The Test-Connection cmdlet is available on Win 8 / Win 2012 R2.   Enjoy.

# Assuming you’ve loaded the PowerCLI snapin located @
# http://blogs.vmware.com/PowerCLI/2014/09/new-release-vmware-vsphere-powercli-5-8-release-1.html
# Loading PowerCLI Snapins
function LoadSnapin{
param($PSSnapinName)
if (!(Get-PSSnapin | where {$_.Name   -eq $PSSnapinName})){
Add-pssnapin -name $PSSnapinName
}
}
LoadSnapin -PSSnapinName   “VMware.VimAutomation.Core”

#An account is needed
$cred = Get-Credential “domain\user”

#Connect to vCenter
Connect-VIServer -server “vCenterServer” -credential $cred
$a = Get-Cluster “Server-Cluster-Name” | get-vm
$results = @()
foreach($computer in $a)
{
Write-Host $Computer.Name
$results += Test-Connection -ComputerName $Computer.Name -count 2
}

$results | Select Address,IPV4Address,ReplySize,ResponseTime | Export-Csv results.csv
Here is a sample output

#TYPE Selected.System.Management.ManagementObject
“Address”,”IPV4Address”,”ReplySize”,”ResponseTime”
“Server1″,”192.168.10.50″,”32″,”0″
“Server1″,”192.168.10.50″,”32″,”0″
“Server2″,”192.168.11.70″,”32″,”0″
“Server2″,”192.168.11.70″,”32″,”0″

VMware Snapshot reminder script

Here is a modified script for sending notifications to owners of Snapshots.    I found a couple of examples I hacked together.  I added a function to help Sanitize based on three different attributes. I consolidated them into a single function that determines to send a notification or not.  We have some static machines used for packaging software that maintain a single snapshot.  I included the two links of the original articles that have notification routines.

I wish the user who created the snapshot would be recorded on each snapshot as the owner.  A person has to retrieve the owner from the tasks / events, which is a bit of extra work.  I’ve been running this script for a couple months and been helpful. 

Enjoy

Steve Schofield
Microsoft MVP – IIS

 

# – SnapReminder V1.0 By Virtu-Al – http://virtu-al.net
#
# Please use the below variables to define your settings before use
# function GetSnapList uses http://virtualcurtis.wordpress.com/2011/10/02/find-virtual-machine-snapshots-with-powercli/
param
(
    [string]$vCenterServer = $(throw “Please specify the vCenter server you want to query for snapshots.”),
    [string]$smtpServer = “mail.example.com”,
    [string]$MailFrom = “steve@example.com”,
    [string]$CredentialID = “domain\user”,
    [int]$AgeOfSnap = 14,
    [string]$Output = “Output”,
    [string]$OutputErrors = “OutputErrors”,
    [string]$OutputEmailAudit = “OutputEmailAudit”   
)

function Log([string]$path, [string]$value)
{
    Add-Content -Path “$($Path)$($LogDate).txt” -Value $value
}

# Loading Snapins
function LoadSnapin{
  param($PSSnapinName)
  if (!(Get-PSSnapin | where {$_.Name   -eq $PSSnapinName})){
    Add-pssnapin -name $PSSnapinName
  }
}
LoadSnapin -PSSnapinName   “VMware.VimAutomation.Core”

function Find-User ($username){
    if ($username -ne $null)
    {
        $usr = (($username.split(“\”))[1])
        $root = [ADSI]””
        $filter = (“(&(objectCategory=user)(samAccountName=$Usr))”)
        $ds = new-object system.DirectoryServices.DirectorySearcher($root,$filter)
        $ds.PageSize = 1000
        $ds.FindOne()
    }
}

function GetSnapList
{

$myVMs = Get-VM
$VMsWithSnaps = @()

foreach ($vm in $myVMs)
{
    $vmView = $vm | Get-View
    if ($vmView.snapshot -ne $null)
    {
         $SnapshotEvents = Get-VIEvent -Entity $vm -type info -MaxSamples 1000 | Where { $_.FullFormattedMessage.contains(“Create virtual machine snapshot”)}
        try
        {
            $user = $SnapshotEvents[0].UserName
            $time = $SnapshotEvents[0].CreatedTime
        }
        catch [System.Exception]
        {
                $user = $SnapshotEvents.UserName
                $time = $SnapshotEvents.CreatedTime
        }
       $VMInfo = “” | Select “VM”,”CreationDate”,”User”
       $VMInfo.”VM” = $vm.Name
       $VMInfo.”CreationDate” = $time
       $VMInfo.”User” = $user
       $VMsWithSnaps += $VMInfo
    }
}

#Causes the array to be doubled
#$VMsWithSnaps | Sort CreationDate

return $VMsWithSnaps
}

function SnapMail ($Mailto, $snapshot)
{
    $msg = new-object Net.Mail.MailMessage
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg.From = $MailFrom
    $msg.To.Add($Mailto)
    $msg.Subject = “Snapshot Reminder”
    $MailText = “This is a reminder that you have a snapshot active on $($snapshot.VM) which was taken on $($snapshot.Created)”       
    $msg.Body = $MailText
    $smtp.Send($msg)
    $VMDiskSize = [Math]::Round(($snapshot.SizeGB),2)
    Log -Path $OutputEmailAudit -Value “$($Mailto),$($snapshot.VM),$($snapshot.Created),$($VMDiskSize) GB”   
}

#Sanitize if a notification is sent to owner of Snap
function Sanitize ($SnapInfo,[string]$VMName)
{
    [string]$SnapDescription=$SnapInfo.Description
    [string]$SnapName=$SnapInfo.Name
   
    switch -wildcard ($VMName)
    {
        “*abc*” {return $false}
        “*xyz*” {return $false}
        “*123*” {return $false}
        “*xp*” {return $false}
        #”*templates*” {return $false}
    }   
   
    switch -wildcard ($SnapDescription)
    {
        “*abc*” {return $false}
        “*xyz*” {return $false}
        “*123*” {return $false}
        “*xp*” {return $false}
        #”*templates*” {return $false}
    }   
   
    switch -wildcard ($SnapName)
    {
        “*abc*” {return $false}
        “*xyz*” {return $false}
        “*123*” {return $false}
        “*xp*” {return $false}
        #”*templates*” {return $false}
        default {return $true}
    }
}

[double]$SnapSpaceUsed=0
[int]$SnapCount=0
$StartDate = Get-Date
$LogDate = “$($StartDate.Month)-$($StartDate.Day)-$($StartDate.Year)-$($StartDate.Hour)-$($StartDate.Minute)-$($vCenterServer)”
$cred = Get-Credential $CredentialID
Connect-VIServer -server $vCenterServer -credential $cred
Log -Path $Output -Value “Starting process as $($Cred.Username) connecting to $($vCenterServer) at $($StartDate)”

$vmlist = GetSnapList

#Get a list of machines that have snapshots
#Loop through it
foreach ($snapdata in $vmlist)
{
    Write-Host “Starting VM – $($snapdata.vm)”
    #Start process that shows creation date is l
     if($snapdata.CreationDate -lt ((Get-Date).AddDays(-$AgeOfSnap)))
    {
      #Get a list of snaphosts per vm
      #Loop through the list of VM’s
      $snapPerVM = Get-VM -Name $snapdata.vm | Get-SnapShot
      foreach($snap in $snapPerVM)
      {           
           [Boolean]$ProcessNotification = Sanitize -SnapInfo $snap -VMName $snapdata.vm
               Log -Path $Output -Value “*************************************************”
            Log -Path $Output -Value “Starting VM – $snapdata.vm”
            Log -Path $Output -Value “Process : $($ProcessNotification) : Snap : $($snap)”
          
           if($ProcessNotification -eq $true -and $snapdata.User -ne $null)
           {
                $mailto = ((Find-User $snapdata.User).Properties)
                $mailattr = $mailto.mail
               
                if($mailattr -ne $null)
                {
                    SnapMail $mailto.mail $snap
                    Write-Host “$($mailto.mail) – $($snapdata.VM) and $($snap)”
                    Log -Path $Output -Value “MailTo Value : $($mailto.mail) : VMName : $($snapdata.VM) : SnapData : $($snap)”                   
                }
                else
                {
                    $FirstName = $mailTo.givenname
                    $LastName = $mailTo.sn
                    $FirstName = $FirstName -replace ” “, “”
                    $LastName = $LastName -replace ” “, “.”
                   
                    if($FirstName -eq $null)
                    {
                        $emailAddress = “steve@example.com”
                    }
                    else
                    {
                        $emailAddress = “$($FirstName).$($LastName)@example.com”
                    }
                   
                    SnapMail $emailAddress $snap
                    Write-Host “$($emailAddress) – $($snapdata.VM) and $($snap)”
                    Log -Path $Output -Value “EmailAddress : $($emailAddress) : VMName : $($snapdata.VM) : SnapData : $($snap)”
                    $emailAddress=””
                }
               
            $SnapCount++
            $SnapSpaceUsed += $snap.SizeGB
           
            Log -Path $Output -Value “Ending VM – $snapdata.vm”
            Log -Path $Output -Value “*************************************************”
           
            }
            else
            {
                Write-Host “Not sending email for $($snapdata) for $($snapdata.VM)”
                Log -Path $OutputErrors -Value ”    Not sending email for VMName : $($snapdata.VM) : SnapData : $($snap)”
            }
        }
    }
   
}

$SnapSpaceUsed = [Math]::Round($SnapSpaceUsed,2)
Log -path $Output -Value “Number of snaps notified via email : $($SnapCount)  `r`nAmount of spaced the snapshots consumed – $($SnapSpaceUsed) GB”

Disconnect-VIServer -Server $vCenterServer -Force -Confirm:$false
$EndDate = Get-Date
Log -Path $Output -Value “Ending process as $($Cred.Username) connecting to $($vCenterServer) at $($EndDate)”

Using CimCmdlets to connect to CIM provider with Powershell and VMware

I needed to retrieve hardware status on memory DIMM’s and used PowerCLI, Powershell to retrieve the data.  Note the script assumes you have a text file list of servers.

#Reference articles
#https://communities.vmware.com/thread/446593
#http://www.virtu-al.net/2012/10/29/using-powershell-v3-0-cim-cmdlets-with-vmware-esxi-hosts/
#http://technet.microsoft.com/en-us/library/jj553783.aspx
#http://www.powertheshell.com/additional-cim-cmdlets-for-download/
#http://blogs.msdn.com/b/powershell/archive/2012/08/24/introduction-to-cim-cmdlets.aspx
#Import-Module : The specified module ‘CimCmdlets’ was not loaded because no valid module file was found in any module directory.

#$Server = “esxiServer1″
#$HostUsername = “root”
#$HostUsername2=Get-Credential
#$CIOpt = New-CimSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck -Encoding Utf8 -UseSsl
#$Session = New-CimSession -Authentication Basic -Credential $HostUsername2 -ComputerName $Ipaddress -port 443 -SessionOption $CIOpt
#$Result = Get-CimInstance -CimSession $Session -ClassName CIM_Chip | where {$_.CreationClassName -eq “OMC_PhysicalMemory” } | Select Caption,DataWidth,FormFactor,MaxMemorySpeed,@{N=”CapacityGB”;E={[math]::Round($_.Capacity/1GB,0)}}

Import-module CimCmdlets

#$HostUsername = “root”
$HostUsername=Get-Credential

$serverlist=get-content -path ServerList.txt
foreach($server in $serverlist)
{
    $CIOpt = New-CimSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck -Encoding Utf8 -UseSsl
    $Session = New-CimSession -Authentication Basic -Credential $HostUsername -ComputerName $server -port 443 -SessionOption $CIOpt
    $Result = Get-CimInstance -CimSession $Session -ClassName CIM_Chip | where {$_.CreationClassName -eq “OMC_PhysicalMemory” } | Select Caption,DataWidth,FormFactor,MaxMemorySpeed,@{N=”CapacityGB”;E={[math]::Round($_.Capacity/1GB,0)}}

    foreach(  in $Result)
    {
        Write-Host $DIMM
    }
}

A new chapter begins virtualization!

I took a position working on VMware recently, I hope to share basic articles I’ve found useful and some personal experiences.  The first thing like any geek, you need to setup the environment to learn how things tick!

With VMware workstation, you can actually host an ESXi server within a guest (who knew!).  I don’t recommend for production, although for learning how things work or getting certification, it’s perfect. 

Nested virtualization (VMware workstation acting as the hypervisor) is sweet.  You’ll need a beefy laptop (SSD drive doesn’t hurt) or workstation with decent amount RAM, CPU and some multiple CPU cores.  I picked up a desktop with 10 GB of RAM, 6 core processor, 1 TB hard disk. 

 

I setup, definitely was easy, there are plenty of articles on the web doing this same thing.

  • Two ESXi servers
  • One domain controller
  • One vCenter server

 

Community

Get a account at https://my.vmware.com/web/vmware/login.   This includes setting up access to the community forums.  

Another thing I started doing was TwinBox with the following search syntax

#esxi OR #esx OR #vsphere OR #vmware OR #VMware OR #vcloud OR #vmwareview OR #vmwaretam

This pulls down some great information from Twitter.  

Enough for now!  Lots to share, and learn.  Take care.

Steve

System Center and Windows 2012 R2 notes

I got a new shiny machine at home with lots of RAM, Disk space and six cores.  This allowed me to setup the following environment

  • Two host machines running windows 2012 R2 with hyper-v
  • 1 domain controller
  • 1 Server running System Center 2012 R2 Orchestrator
  • 1 Server running System Center 2012 R2 operations manager
  • 1 Server running System Center 2012 R2 configuration manager

 

I downloaded the evaluations from MSDN and evaluation center. 

OS
http://technet.microsoft.com/en-us/evalcenter/dn205286.aspx

SCCM
http://technet.microsoft.com/en-US/evalcenter/dn205297

I downloaded Orchestrator and SCOM from MSDN

For the most part, everything installed cleanly.  A few to-do’s I have yet to confirm and figure out

  • Windows firewall being enabled
  • SQL RM0 Error when installing SCCM.  I found the sqlclini.msi was zero byte file.  I downloaded an SCCM 2012 SP1 version.  Once I copied the \\server1$\Apps\SC2012_R2_PREVIEW_SCCM_SCEP\SMSSETUP\BIN\X64\sqlncli.msi, SCCM installed cleanly. 
  • I’ve also ran into a couple issues where the default gateway wouldn’t set, one on my domain controller.  After I ran route delete 0.0.0.0 and set it manually a couple times, things worked. 

 

I’m in the process of adding SCVMM 2012 R2 to another server.  I have to P2V my one host, which is running windows 2012 w/SP1.  This will allow me to learn the P2V and also update my one host to Server 2012 R2.  I tried to allow live replication between my one host running 2012 SP1 and 2012 R2.  I get an error.  I’m not a VM guru, so this hopefully learn a bit more about SCVMM, App Controller

Other goals…

  • Learn OSD
  • Live Replication
  • P2V
  • SCCM Application module
  • APM management pack

 

Stay tuned for more blog posts.  Oh btw, I’ll be tinkering with IIS 8.5 and the new logging features

Happy Geeking,

Steve Schofield

Microsoft MVP – IIS

Just another IISLogs.com site