vendredi 11 septembre 2015

Retrieving a VM Snapshot path from vCenter using Powershell

Sometime, retrieving the path of a VMware VM's Snapshot can prove useful.

As we've had to automate the deployment of some VMware Horizon Pools using Powershell, the cmdlet Add-AutomaticLinkedCLonePool was asking for a Snapshot path as an input with the "ParentSnapshotPath" parameter.

So here's the function that answered this need!

#Requires -Version 3.0


Function Get-VMSnapshotPath {

<#

    .SYNOPSIS

            This function will return a VM's Snapshot path

    .DESCRIPTION

            This function will return a VM's Snapshot path

    .PARAMETER  Snapshot

            Specifies a VM Snapshot

    .EXAMPLE

            Get-Snapshot -VM (Get-VM "Master") -Name "BaseSnapshot" | Get-VMSnapshotPath


            /BaseSnapshot

    .EXAMPLE

            Get-Snapshot -VM (Get-VM "Master") -Name "SecondSnapshot" | Get-VMSnapshotPath


            /BaseSnapshot/SecondSnapshot

    .EXAMPLE

            (Get-VM "Master"), (Get-VM "MasterVDI") | Get-Snapshot | Get-VMSnapshotPath


            /BaseSnapshot

            /BaseSnapshot/SecondSnapshot

            /VDIBaseSnapshot

    .NOTES

            NAME:     Get-VMLogicalPath

            AUTHOR:   ROULEAU Benjamin

            LASTEDIT: 2015-02-05

    .LINKS

            http://katalykt.blogspot.fr/

#>

    [CmdletBinding()]

    PARAM(

        [Parameter(

            Mandatory,

            ValueFromPipeline,

            ValueFromPipelineByPropertyName)]

        [VMware.VimAutomation.ViCore.Impl.V1.VM.SnapshotImpl]$Snapshot

    )


    BEGIN {

        

    }


    PROCESS {

        $Snapshot | ForEach-Object {

            Write-Verbose -Message ("[PROCESS - Get-VMSnapshotPath] Retrieving the path of Snapshot: '{0}' on VM : '{1}'" -f $_.Name, $_.VM.Name)


            # We retrieve the Snapshot path up the the root of the VM

            $VMo = $_

            $Path = ""

            WHILE ($VMo) {

                $Path = "/" + $VMo.Name + $Path

                $VMo = $VMo.ParentSnapshot

            }


            $Path

        }

    }


    END {


    }

}

mercredi 8 juillet 2015

Retrieving big files through Powershell

Sometime, when you need to do some cleanup on your workstation or on a file server you may want to get a list of files which exceed a given size threshold.

Thanks to Powershell we can do this in an easy way!

#requires -version 3


Function Get-BigFiles {

<#

    .SYNOPSIS

            This function will scan a folder in order to retrieve the files which exceed a given

            size threshold

    .DESCRIPTION

            This function will scan a folder in order to retrieve the files which exceed a given

            size threshold

    .PARAMETER  Path

            Specifies the folder to scan recursively

    .PARAMETER  MinSize

            Specifies the minimal threshold

    .EXAMPLE

            Get-BigFiles -Path "D:\temp\vsphere6.1"


            FullName                      Date Created             Date Modified            Size (MB)

            --------                      ------------             -------------            ---------

            D:\temp\vsphere6.1\VMware-... 20/05/2015 12:07:33      20/05/2015 11:50:35         2613,7

            D:\temp\vsphere6.1\vRealiz... 16/06/2015 11:04:43      11/06/2015 11:52:31        1503,97

            D:\temp\vsphere6.1\VMware-... 29/06/2015 13:41:37      29/06/2015 13:39:12          868,5

            D:\temp\vsphere6.1\VMware-... 29/06/2015 14:04:48      29/06/2015 14:03:34         867,63

            D:\temp\vsphere6.1\vRealiz... 16/06/2015 11:03:56      15/06/2015 12:10:53         404,82

            D:\temp\vsphere6.1\VMware-... 20/05/2015 12:08:54      20/05/2015 11:56:10         348,38

            D:\temp\vsphere6.1\VMware-... 20/05/2015 12:09:31      20/05/2015 10:06:22         171,72

            D:\temp\vsphere6.1\VMware-... 20/05/2015 12:09:16      20/05/2015 10:05:25         119,95

            D:\temp\vsphere6.1\VMware-... 17/06/2015 09:35:40      11/06/2015 11:23:47          35,82

            D:\temp\vsphere6.1\VMware-... 20/05/2015 12:09:20      20/05/2015 10:03:19          31,33

    .EXAMPLE

            Get-BigFiles -Path "D:\temp\vsphere6.1" -MinSize 1Gb


            FullName                      Date Created             Date Modified            Size (MB)

            --------                      ------------             -------------            ---------

            D:\temp\vsphere6.1\VMware-... 20/05/2015 12:07:33      20/05/2015 11:50:35         2613,7

            D:\temp\vsphere6.1\vRealiz... 16/06/2015 11:04:43      11/06/2015 11:52:31        1503,97


    .EXAMPLE

            "D:\temp\vsphere6.1" | Get-BigFiles -MinSize 750Mb


            FullName                      Date Created             Date Modified            Size (MB)

            --------                      ------------             -------------            ---------

            D:\temp\vsphere6.1\VMware-... 20/05/2015 12:07:33      20/05/2015 11:50:35         2613,7

            D:\temp\vsphere6.1\vRealiz... 16/06/2015 11:04:43      11/06/2015 11:52:31        1503,97

            D:\temp\vsphere6.1\VMware-... 29/06/2015 13:41:37      29/06/2015 13:39:12          868,5

            D:\temp\vsphere6.1\VMware-... 29/06/2015 14:04:48      29/06/2015 14:03:34         867,63

    .NOTES

            NAME:     Get-BigFiles

            AUTHOR:   ROULEAU Benjamin

            LASTEDIT: 2015-07-07

    .LINKS

            http://katalykt.blogspot.fr/

#>


    [CmdletBinding()]

    PARAM(

        [Parameter(

            Mandatory,

            ValueFromPipeline,

            ValueFromPipelineByPropertyName)]

        [ValidateScript({Test-Path -Path $_ -PathType Container})]

        $Path,

        

        [ValidateScript({$_.GetType().Name -eq "Int32"})]

        $MinSize=25Mb

    )


    BEGIN {

        Write-Verbose -Message "[BEGIN] Scan began at: $((Get-Date).ToString("yyyy-MM-dd HH:mm:ss"))"

    }


    PROCESS {

        Write-Verbose -Message "[PROCESS] Scanning folder: $Path"


        # Get the content of the given folder and fetch files which are higher than the given size threshold

        Get-ChildItem -Path $Path -Recurse -ErrorAction "SilentlyContinue" |

            Where-Object {$_.Length -ge $MinSize} |

            Select-Object FullName, `

                @{Name="Date Created";Expression={$_.CreationTime.ToString()}}, `

                @{Name="Date Modified";Expression={$_.LastWriteTime.ToString()}}, `

                @{Name="Size (MB)";Expression={[math]::Round($_.Length / 1Mb, 2)}} |

            Sort-Object "Size (MB)" -Descending

    }


    END {

        Write-Verbose -Message "[END] Scan ended at: $((Get-Date).ToString("yyyy-MM-dd HH:mm:ss"))"

    }

}

mercredi 10 juin 2015

Retrieving a VM's Logical Path from vCenter using Powershell

In some cases, knowing a Virtual Machine’s Logical Path can be quite useful when the need to perform automated tasks in VMware arise.

One of our objectives during our last VMware Horizon View deployment was to automate the creation of multiple Automatic Linked Clone pools. As a matter of fact, the Cmdlet linked to the pool’s creation (Add-AutomaticLinkedCLonePool) has two parameters which expect both the VM’s Full Path and the path to its Parent Folder.

The PowerShell Function below expects a VM as a parameter and returns the VM’s name, its Full Path and its Parent Folder’s path as shown in the synopsis. Just what we needed for our automation process!

#requires -version 2


Function Get-VMLogicalPath {

<#

    .SYNOPSIS

            This function will return a VM's logical path within vCenter

    .DESCRIPTION

            This function will return a VM's logical path within vCenter with or without the VM's name

    .PARAMETER  VM

            Specifies a vCenter VM

    .EXAMPLE

            Get-VMLogicalPath -VM (Get-VM -Name "Master")


            Name                 VMPath                                        ParentPath                                          

            ----                 ------                                        ----------                                          

            Master               /KatalyktDC/vm/PoolFolder/Master              /KatalyktDC/vm/PoolFolder  

    .EXAMPLE

            $VMArray | Get-VMLogicalPath


            Name                 VMPath                                        ParentPath                                          

            ----                 ------                                        ----------                                          

            Master               /KatalyktDC/vm/PoolFolder/Master              /KatalyktDC/vm/PoolFolder  

            MasterTraining       /KatalyktDC/vm/PoolFolder/MasterTraining      /KatalyktDC/vm/PoolFolder  

    .NOTES

            NAME:     Get-VMLogicalPath

            AUTHOR:   ROULEAU Benjamin

            LASTEDIT: 2014-02-05

    .LINKS

            http://katalykt.blogspot.fr/

#>

    [CmdletBinding()]

    PARAM(

        [Parameter(

            Mandatory=$true,

            ValueFromPipeline=$true,

            ValueFromPipelineByPropertyName=$true)]

        [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl]$VM

    )


    BEGIN {

        

    }


    PROCESS {

        $VM | ForEach-Object {

            TRY {

                Write-Verbose -Message ("[PROCESS - Get-VMLogicalPath] Retrieving path for VM {0}" -f $_.Name)


                # We keep retrieving the parent's folder up to the Datacenter root

                $VMo = $_.Folder

                $Path = ""

                WHILE ($VMo) {

                    $Path = "/" + $VMo.Name + $Path

                    $VMo = $VMo.Parent

                }


                # Compose the VM Path

                $VMPath = $Path + "/" + $_.Name

                

                Write-Verbose -Message ("[PROCESS - Get-VMLogicalPath] Retrieved path {0} for VM {1}" -f $VMPath, $_.Name)


                # Return the desired properties in an object

                New-Object -TypeName PSObject -Property @{

                    Name = $_.Name

                    ParentPath = $Path

                    VMPath = $VMPath

                }

                

            } CATCH {

                Write-Warning -Message ("[PROCESS - Get-VMLogicalPath] Something went wrong: {0}" -f $Error[0].Exception.Message)

            }

        }

    }


    END {


    }

}

vendredi 3 octobre 2014

Replacing SSL Certificates for VMware Horizon View 5.2

While replacing the default SSL Certificates in the vSphere suite could seems challenging, the process in the View suite is much easier.

This article will cover the replacement of the default SSL certificates for both VMware View Connection Server and VMware View Composer.

OpenSSL and a Windows 2008 R2 CA are used to generate our CA Signed SSL certificates.

As a reminder, View Composer can be installed on the vCenter server or on another server (in case of heavy load).

My domain katalykt.lan is designed as follow:
- dc0001.katalykt.lan: This is the domain controller and our Certification Authority.
- vc0001.katalykt.lan: This is the vCenter and our View Composer server.
- cs0001.katalykt.lan: This is our View Connection Server.

Let's start by creating our working directory, under

C:\OpenSSL-Win32\Certificates


Let's create the following folders:

  • Composer
  • ConnectionServer


Creating the OpenSSL Template files

In this part, we'll create a configuration file for those folders in their respective folder:

Composer.cfg
[ req ]
default_bits = 2048
default_keyfile = rui.key
distinguished_name = req_distinguished_name
encrypt_key = no
prompt = no
string_mask = nombstr
req_extensions = v3_req
 
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = DNS:vc0001, DNS:vc0001.katalykt.lan
 
[ req_distinguished_name ]
countryName = FR
stateOrProvinceName = Normandie
localityName = Caen
0.organizationName = Katalykt
organizationalUnitName = ViewComposer
commonName = vc0001.katalykt.lan

ConnectionServer.cfg
[ req ]
default_bits = 2048
default_keyfile = rui.key
distinguished_name = req_distinguished_name
encrypt_key = no
prompt = no
string_mask = nombstr
req_extensions = v3_req
 
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = DNS:cs0001, DNS:cs0001.katalykt.lan
 
[ req_distinguished_name ]
countryName = FR
stateOrProvinceName = Normandie
localityName = Caen
0.organizationName = Katalykt
organizationalUnitName = ConnectionServer
commonName = cs0001.katalykt.lan


Creating the SSL Certificates CA Template

A specific CA SSL Certificate Template is required for VMware View. See my article about Preparing a Microsoft CA SSL Certificate Template for VMware View 5.2 here to create one.

I've granted my service account srv-vcenter the right to Enroll my VMwareViewSSL Template here (this is done by modifying the template)



Generating the SSL Certificates

So now that we've got everything that we need we can just go ahead and create a script which will do the manual labor for us!

This script will do as follow for each component:
  • Create a private key rui.key in RSA 2048
  • Create a Certificate Signing Request from the current OpenSSL Template
  • Submit the previous request to the CA and (hopefully) generate the Certificate rui.crt
  • Create the Personal Information Exchange file which will bundle our Certificate along with its private key
Create_View_SSL.bat
REM Change this according to your needs
Set OPENSSL=c:\OpenSSL-Win32\bin\openssl.exe
Set SSLPATH=c:\OpenSSL-Win32\Certificates
Set MSCA=DC0001\katalykt-DC0001-CA
Set MSCATEMPLATE=VMwareViewSSL
  
REM Core processing
echo PROCESSING: View Composer SSL Certificate
cd /d %SSLPATH%\Composer
%OPENSSL% genrsa 2048 > rui.key
%OPENSSL% req -out rui.csr -key rui.key -new -config Composer.cfg
certreq -submit -config %MSCA% -attrib "CertificateTemplate:%MSCATEMPLATE%" rui.csr rui.crt
%OPENSSL% pkcs12 -export -in rui.crt -inkey rui.key -name vdm -passout pass:testpassword -out rui.pfx
  
echo PROCESSING: View Connection Server SSL Certificate
cd /d %SSLPATH%\ConnectionServer
%OPENSSL% genrsa 2048 > rui.key
%OPENSSL% req -out rui.csr -key rui.key -new -config ConnectionServer.cfg
certreq -submit -config %MSCA% -attrib "CertificateTemplate:%MSCATEMPLATE%" rui.csr rui.crt
%OPENSSL% pkcs12 -export -in rui.crt -inkey rui.key -name vdm -passout pass:testpassword -out rui.pfx


Replacing the View Composer Certificate

If you already have a View Connection Server up and linked to an existing View Composer then make sure to stop it's services before replacing View Composer SSL certificate.

As you may already know, View Composer is installed either on the vCenter or on a side server. In this case it's hosted on my vCenter.

The first step is to stop the VMware View Composer service before proceeding any further.


The goal of this operation is to import our previously generated Personal Information Exchange rui.pfx into the View Composer server Personal store so that it may use both the SSL Certificate along with its private key.

So we hit the mmc.exe component where the View Composer is installed and load the Certificates Snap-in.


We pick the Computer account here.


I'm picking Local computer here since the mmc snap-in is running on the View Composer server.


Once the operation done, we browse to Personal >> Certificates. If you already have View Composer installed then you should be able to see the default Self Signed SSL Certificate in there.


The next step is to import our rui.pfx into the Certificates folder.

Using the contextual menu on the Certificates folder we do All Tasks > Import... to import it in there.

The first thing is to select the View Composer's rui.pfx file.


We use the password testpassword here (if you haven't changed it from the script that is) and we absolutely need to mark the key as exportable by ticking the option Mark this key as exportable...


Finally we place it in the Personal store.


Once done, we should be able to see our SSL certificate in the Personal store!


If you open up your SSL certificate you should see that a private key is associated with it thanks to the message "You have a private key that corresponds to this certificate".

If the SSL certificate doesn't have an associated private key then the replacement will not work (remember that the SSL Certificate template need to allow the private key export!)


Now that we got our SSL Certificate in our Personal store we can go ahead and replace the existing one.

This step is done by using the SviConfig.exe tool present on the View Composer server.

"c:\Program Files (x86)\VMware\VMware View Composer\SviConfig.exe" -operation=replacecertificate -delete=false

Note that we put the delete switch on false to keep the existing SSL Certificate in the store (we can always delete it later on)

Once the utility launch, simple select the new SSL certificate and everything else will be done automatically!


You may delete (or export as a backup) the old Certificate now.

And that's it! Our View Composer certificate has been changed! Make sure to restart the service!


Replacing the View Connection Server Certificate

View Connection Server SSL Certificate replacement is quite similar to the View Composer's one.

Our last rui.pfx has to be loaded onto the Connection Server personal certificate store. The only difference is that its "friendly name" need to be called vdm (It will only look for SSL Certificates with that friendly name)

Replacing the SSL Certificate of the View Connection Server is a good practice for many reasons. For instance your clients will view the Connection Server as a valid CA Signed entity when they connect through the View Horizon Client (No more red warning about Self Signed yay!)

Let's start our operation by stopping all View components services.


Via the mmc.exe component on the View Connection Server we add the Certificates Snap-in and load the Computer Account (This is the same process as the Composer's one above) on the Local computer.

Once more, we have the default SSL Certificate in there!


The next step is to import our rui.pfx into the Certificates folder.

Using the contextual menu on the Certificates folder we do All Tasks > Import... to import it in there.

The first thing is to select the View Connection Server rui.pfx file.


We use the password testpassword here (if you haven't changed it from the script that is) and we absolutely need to mark the key as exportable by ticking the option Mark this key as exportable...


Finally we place it in the Personal store.


Right now we have both the old and the new SSL Certificate. Make sure that the new SSL Certificate has the "vdm" Friendly Name set otherwise it will not be loaded.


I've removed the old SSL Certificate (you can export it too).


Finally we can restart the View Connection Server services.


After a few minutes, we head to the Web Admin site to ensure that the new SSL Certificate is loaded

https://cs0001.katalykt.lan/admin

If everything's fine our dashboard should show that our Connection Server is healthy!



Integrating View Composer in View Connection Server

In this part, I'll be linking my View Composer to my View Connection Server. If you already did it then you may skip this part.

Let's head in View Configuration >> Servers and add a vCenter server.


In my case the Composer is linked to the vCenter.



My vCenter is added as shown below.


The dashboard shows our View Composer's SSL Certificate as valid! (It may appear red at first but give it a few minutes)


Both our View Connection server and View Composer are now using valid CA SSL Certificates!

jeudi 2 octobre 2014

Preparing a Microsoft CA SSL Certificate Template for VMware View 5.2

Preparing an SSL Certificate Template for VMware View 5.2 is quite easy compared to the other vCenter components. What we have to keep in mind in this case is that the Private Key need to be exportable since both View Composer and View Connection Server requieres that option.

First of all let's go in our Certification Authority to find our Certificate Templates And select Manage from the contextual menu (or you may use the shortcut certtmpl.msc to go straight to the template console)


Now let's duplicate our Web Server template by using the contextual menu action Duplicate Template


We pick Windows Server 2003 Enterprise as a Minimal Supported CA


We can now start to customize our View SSL Template.

Let's start by giving it a descriptive label like VMware View SSL (note the difference between the display name and the template name, the display name has some escape characters while the template name doesn't).

Our template will be refered as VMwareViewSSL later on.


Our template should only be used for Server Authentication as we don't need Client Authentication here.


Next we're going to Edit the Key Usage.


We tick Allow encryption of user data


In the Request Handling tab, the most important part is to tick the option Allow private key to be exported.


We do a quick check in the Subject Name tab to ensure that the Supply in the request option is ticked. This is important for the Subject Alternative Name (SAN) property.


We validate the creation of our template and we should be able to see it among our templates


We quit the Template console and we're back in our CA's Menu.

Let's enable the template by using New >> Certificate Template to Issue  from the contextual menu over the Certificate Templates folder


Once that we're in the Enable Certificate Templates menu, we choose our VMware View SSL template and we validate.


Our Template is now issued and ready to be used!