PowerCLI: Copy Datastore Items


In this short post I will show a PowerCLI script I wrote to copy ISO files from datastore y to datastore x. The datastores are in the same vCenter and virtual datacenter accessible but the vSphere hosts are located inside two different IP subnets and a firewall rule prevents to copy files between the two subnets. So I had to think about a work around. Well this one is easy. On the vCenter server I created a script to peform the following steps:

  1. Create two PSDrives for each Datastore
  2. Get al the ISO filenames
  3. Downlad the ISO to the c:\tmp directory from datastore y
  4. Upload the ISO from the C:\tmp directory to the datastore<X>\iso directory
  5. Remove the ISO from C:\tmp
  6. repeat the steps above until all the ISO files are copied to the new datastore.

The PowerCLI script to perform the described tasks:

New-PSDrive -location (get-datastore template-01) -name tpl01 -PSProvider VimDatastore -Root '\'
New-PSDrive -location (get-datastore template-02) -name tpl02 -PSProvider VimDatastore -Root '\'

$isos = ls tpl01:\iso\ | % {$_.Name}
foreach($iso in $isos){
    Write-Host "copy $($iso) to C:\tmp" -fore Yellow
    Copy-DatastoreItem -item tpl01:\iso\$iso -Destination C:\tmp
    
    Write-Host "copy $($iso) to template-02\iso" -fore Yellow
    Copy-DatastoreItem -item C:\tmp\$iso -Destination tpl02:\iso
    
    Write-Host "removing the tmp file $($iso) from C:\tmp" -fore Yellow
    Remove-Item C:\tmp\$iso -confirm:$false
    
    Write-Host "done" -fore Green
}

So once again PowerCLI to the rescue.

PowerCLI: Disable / Enable HA Host Monitoring


In the case you need to or your network team needs to do some network maintenance on the switches which VMware HA uses to communicate with the other hosts or where the das.isolationaddress (default gateway) is configured/ It’s smart to disable the Host Monitoring feature of VMware HA. You can do this easily by hand via edit cluster – VMware HA and uncheck the Enable Host Monitoring feature. See screenshot below:

image

But what if you have to disable Host Monitoring on multiple VMware HA cluster? Well, if you like PowerCLI, you can use the following script to disable or enable the HA Host Monitoring feature:

param(
    $vCenter,
    $option
)

if($vCenter -eq $null){
    Write-Host "Please enter the name of the vCenter Server" -ForegroundColor Yellow
    exit 
} 

switch($option){
    enabled {"The HA Host Monitoring feature will be enabled"}
    disabled {"The HA Host Monitoring feature will be disabled"}
    default {"the option value could not be determined."
    exit
    }
}

Connect-VIServer $vCenter

$clspec = New-Object VMware.Vim.ClusterConfigSpecEx
$clspec.dasConfig = New-Object VMware.Vim.ClusterDasConfigInfo
$clspec.dasConfig.hostMonitoring = $option

foreach($cluster in (Get-Cluster | sort Name)){
    $clview = Get-Cluster $cluster | Get-View
    $clview.ReconfigureComputeResource_Task($clspec, $true)
}

Disconnect-VIServer -Confirm:$false

Just save the script to change-HAHostMonitoring.ps1 and run it like this to disable the HA Host Monitoring feature:

Change-HAHostMonitoring vcenter.domain.loc disabled

If you want to enable Host Monitoring, just change disabled to enabled:

Change-HAHostMonitoring vcenter.domain.loc enabled

Note: Please test the script mentioned in this blog post in a lab or test environment before you use the script in a production environment.

PowerCLI: Migrate templates during the Enter Maintenance Mode task


Normally when you put a host into Maintenance mode the templates will stay on the host instead of being migrate to a different host. This can be very annoying if you are performing maintenance on the vSphere host and a colleague needs to deploy a VM from the template. I am running vSphere 4.1 update 1. I don’t know if this is still the case with vSphere 5. The host in Maintenance mode will look like this:

image

So to fix this annoying “issue” I have created a PowerCLI function to place the vSphere host into maintenance mode and if there are Templates registered on the vSphere host, the Templates will be moved to another host in the Cluster.

Function Enter-MaintenanceMode{
<#
.SYNOPSIS   Enter Maintenance mode 
.DESCRIPTION   The function starts the Enter Maintenance task and also migrates the Templates to another host.
.NOTES   Author:  Arne Fokkema
.PARAMETER vmHost
   One vmHosts.
.EXAMPLE
   PS> Enter-MaintenanceMode<vmHost Name>
.EXAMPLE
  PS> Get-VMHost <vmHost Name> | Enter-MaintenanceMode
#>

[CmdletBinding()]
param(
    [parameter(ValueFromPipeline = $true,
    position = 0,
    Mandatory = $true,
    HelpMessage = "Enter the vmHost to start the Enter Maintenance mode task")]
    $vmHost
)    

    $templates = Get-VMHost $vmHost | Get-Template
    if($templates -eq $null){
        $tplMigrate = $false
    }
    else{
        $tplMigrate = $true
    }
    
    $targetVMHost = Get-VMHost -Location (Get-Cluster -VMHost (Get-VMhost $vmHost)).Name | Where {$_.Name -ne $vmHost} | Sort Name | Select -First 1
    if($tplMigrate -eq $true){
        foreach($tpl in $templates){
            Write-Host "Converting template $($tpl.Name) to VM" -ForegroundColor Yellow
            $vm = Set-Template -Template (Get-Template $tpl) -ToVM 
            
            Write-Host "Moving template $($tpl.Name) to vmHost: $($targetVMHost)" -ForegroundColor Yellow
            Move-VM -VM $vm -Destination (Get-VMHost $targetVMHost) -Confirm:$false | Out-Null
            
            Write-Host "Converting template $($tpl.Name) back to template" -ForegroundColor Yellow
            ($vm | Get-View).MarkAsTemplate() | Out-Null    
        }    
    }
    Write-Host "Enter Maintenance mode $($vmHost)" -ForegroundColor Yellow
    Set-VMHost $vmHost -State Maintenance | Out-Null
}

You can run the script like this:

Enter-MaintenanceMode esx07

Or from the pipeline:

Get-VMHost esx07 | Enter-MaintenanceMode

The output will be the same:

image

And the host is completely empty and ready for maintenance:

image

Disconnect ISO files from Templates with PowerCLI


Just a quick post about how to disconnect ISO files from templates with PowerCLI.  With the following script you can set the CD Drive to No Media. So the ISO files will be disconnected from the Template VMs.

$templates = Get-Template 
foreach($tpl in $templates){
    $vm = Set-Template -Template (Get-Template $tpl) -ToVM 
    Get-CDDrive -VM $vm | Set-CDDrive -NoMedia -Confirm:$false | Out-Null
    ($vm | Get-View).MarkAsTemplate() | Out-Null
}

First the script will fill the templates variable with all the templates available. The next step is to convert the Template back to a VM. When the template is converted to a VM the Get-CDDrive cmdlet is used to set the CD Drive to No Media. When the CD Drive is configured the VM will be converted back to a template. In stead of nine mouse clicks per template you can lean back and drink your cup of coffee or thee and see the magic powered by PowerCLI.

How to copy ISO files between datastores via PowerCLI


We decided to replace our current central ISO datastore to a new one on different storage. You can use the CP commend on the Service Console, if you’re still running ESX classic. But I wanted to investigate if there was a way to do this with PowerCLI. Well there is cmdlet for that called Copy-DatastoreItem. In the PowerCLI help you will find something like this:

Copy-DatastoreItem

Synopsis Copies items between datastores and between a datastore and a local file system provider.

Syntax Copy-DatastoreItem [-Item] [[-Destination]] [-Force] [-PassThru] [-Recurse] [-WhatIf] [-Confirm]

But how do you find the datastore where you want to copy files from?  Well you need to keep in mind the following two objects. The Folder, if you created one (1) and the Datacenter where the Datastore belongs to (2):

image

Now that you know the path to the datastore containing the files you want to copy. You can start PowerCLI and connect to your vCenter server. Before you continue, you need to create a temp directory to temporarily save the ISO files in. In my case this is E:\iso. The one-liner will look like this:

Copy-DatastoreItem vmstore:\Alkmaar\DataCenter\template-01\iso\* E:\iso

And now we wait until the files are copied to the temp directory:

image

The next step is to copy the files from the temp directory to the new datastore.

Copy-DatastoreItem E:\iso\* vmstore:\DataCenter\template-01\iso\

And we wait again:

image

How to return HP Serial Number via iLO and Powershell


Robert van den Nieuwendijk created the basis of this script and shared it on the VMware Communities. The problem I had with the original script was the default SSL certificate which HP uses on the iLO adapters. This resulted in an error and the script failed to return the XML file. So I started a search query on Google and found a post by Paul Brice who had the same problem while getting information via XML on an Iron Port setup. I tried his code to open the iLO XML information and it worked like a charm.

So I updated the script from Robert and added the information from Paul to it. The last thing I changed was the $url and added a RegEx to return the digits from the ESX hostname. For example esx72, the RegEx will return the 72.

Get-VMHost | Where-Object {$_.Manufacturer -eq "HP"} | `
Sort-Object -Property Name | ForEach-Object {
    $VMHost = $_
    $netAssembly = [Reflection.Assembly]::GetAssembly([System.Net.Configuration.SettingsSection])
    IF($netAssembly) {
        $bindingFlags = [Reflection.BindingFlags] "Static,GetProperty,NonPublic"
        $settingsType = $netAssembly.GetType("System.Net.Configuration.SettingsSectionInternal")
        $instance = $settingsType.InvokeMember("Section", $bindingFlags, $null, $null, @())
        
        if($instance) {
            $bindingFlags = "NonPublic","Instance"
            $useUnsafeHeaderParsingField = $settingsType.GetField("useUnsafeHeaderParsing", $bindingFlags)

            if($useUnsafeHeaderParsingField) {
                $useUnsafeHeaderParsingField.SetValue($instance, $true)
            }
        }
    }

    [int]$ip = (([regex]'\d+').matches($vmhost.Name) | select Value).Value

    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
    $url = "https://192.168.1.$ip/xmldata?item=All"
    $xml = New-Object System.Xml.XmlDocument
    $xml.Load("$url")
        New-Object PSObject -Property  @{
            "Name" = $VMHost.Name
            "Serial Number" = $xml.RIMP.HSI.SBSN
            "ILO Serial Number" = $xml.RIMP.MP.SN
            "ILO Type" = $xml.RIMP.MP.PN
            "ILO Firmware" = $xml.RIMP.MP.FWRI    
          }
} | Export-Csv -NoTypeInformation -UseCulture -Path C:\EsxSerialNumbers.csv 

The output of the script will be exported to a CSV file.

Disk Hard disk # has incorrect changed block tracking configuration


Today another Veeam troubleshooting trick. It’s possible that you’ll receive the following error in one of your Veeam Backup Jobs:

Verifying change block tracking:
Disk “Hard disk 1” has incorrect changed block tracking configuration

This is how it looks like in the Veeam Backup console:

image

The procedure which Veeam describes in the solution for this problem works like this:

  1. Shutdown the VM
  2. VM – Edit Settings – Options – General – Configuration Parameters…
  3. Change every item with ctkEnabled to false
  4. Start the VM
  5. Start the Backup Job to see if this is the solution for this problem.
  6. This is how you change the parameter to false:

image

In my case, the above solution did not solve the problem. So I had to troubleshoot the VM. While checking the configuration a noticed that the Disk was configured with the Independent mode enabled. You can change this setting when the VM is powered off. Go to Hardware, select the Hard disk and disable the checkbox by Independent:

image

The setting above can only be changed when the VM is powered off, if you’re using the vSphere client. It’s also possible to change this setting, on-the-fly with PowerCLI. That rimes Winking smile.

You can run the following one-liner to disable the Independent mode:

Get-VM <vmName> | % { Get-HardDisk -VM $_ | Where {$_.Persistence -eq "IndependentPersistent"} | `
% {Set-HardDisk -HardDisk $_ -Persistence "Persistent" -Confirm:$false} }

Disclaimer: this one-liner worked for me in my environment but test this first because I don’t know exactly what the impact is of this change.

PowerCLI: Easy iSCSI Send Target setup


In January this year I created a post about Easy NFS datastore setup with PowerCLI. In this post I showed how you can use a reference host to copy all the NFS share configurations to the new host. In this post I will show you how to do the exact same thing only for iSCSI Send targets. I finally find some time to write this post which I promised to write in part 2 of my PowerCLI and iSCSI series.

The following script will check the $REFHOST, in my case esx2.ict-freak.local for all the iSCSI Send targets configured on that host. After that the script will check if all the iSCSI Send targets exists on the $NEWHOST. If this is not the case the script will add the missing Send Targets.

$REFHOST = Get-VMHost "esx2.ict-freak.local"
$NEWHOST = Get-VMHost "esx1.ict-freak.local"

$REFHBA = Get-VMHostHba -VMHost $REFHOST -Type iScsi | Where {$_.Model -eq "iSCSI Software Adapter"}
foreach($target in (Get-IScsiHbaTarget -IScsiHba $REFHBA -Type Send)){
    $target = $target.Address
        $NEWHBA = Get-VMHostHba -VMHost $NEWHOST -Type iScsi | Where {$_.Model -eq "iSCSI Software Adapter"}
        If ((Get-IScsiHbaTarget -IScsiHba $NEWHBA -Type Send | Where {$_.Address -eq $target} -ErrorAction SilentlyContinue )-eq $null){
            Write-Host "Target $($target) doesn't exist on $($NEWHOST)" -fore Red
            New-IScsiHbaTarget -IScsiHba $NEWHBA -Address $target | Out-Null
        }        
}

But there is more..

Continue reading

PowerCLI: Return the iSCSI Software Adapter


In my previous postsabout how to manage iSCSI targets with PowerCLI part 1 and part 2. I used the following line to return the iSCSI adapter:

$hba = $esx | Get-VMHostHba -Type iScsi

But when I used this line against a vSphere 4.1 update 1 host with Broadcom BCM5709 (Dell Poweredge R710). vSphere will use these adapters as Broadcom iSCSI Adapters. And when you run the $hba = $esx | Get-VMHostHba -Type iScsi one-liner, it will return all the vmhba adapters.

[vSphere PowerCLI] C:\> $esx | Get-VMHostHba -Type iScsi

Device     Type         Model                          Status

——     —-         —–                          ——

vmhba32    IScsi        Broadcom iSCSI Adapter         unbound

vmhba33    IScsi        Broadcom iSCSI Adapter         unbound

vmhba34    IScsi        Broadcom iSCSI Adapter         unbound

vmhba35    IScsi        Broadcom iSCSI Adapter         unbound

vmhba37    IScsi        iSCSI Software Adapter            online

This “problem” can easily be resolved with a Where statement. In the following Where statement you look for a Model that equals “iSCSI Software Adapter”. There is only one Software adapter in ESX(i) so it will return the right vmhba. The PowerCLI line will look like this:

$esx | Get-VMHostHba -Type iScsi | Where {$_.Model -eq "iSCSI Software Adapter"} 

[vSphere PowerCLI] C:\> $esx | Get-VMHostHba -Type iScsi | Where {$_.Model -eq "iSCSI Software Adapter"}

Device     Type         Model                          Status

——     —-         —–                          ——

vmhba37    IScsi        iSCSI Software Adapter         online

So the bottom line. Test your code on different setups and update it when necessary 😉

PowerCLI: Error 1406. Could not write value InstallPath to key….


Today I wanted to install PowerCLI on a new installed Windows 2008 R2 server. But I ended up with the following warning:

image

To fix this, you have to delete the following Registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\VMware, Inc.

And press retry. The PowerCLI setup will finish without errors.

 

Source: http://www.annoying.dk