Migrate ESXi virtual machines to a different datastore using Powershell

13. April 2012

I needed to perform a bulk move of all the virtual machines running on an ESXi Host to a NAS storage device so that I could rebuild the RAID array. Needed an easy way to perform this move, so i used powerCLI and it was very easy.

The following PowerCLI script will do this. It will even perform a storage vMotion if the VM is running but only if there are no snapshots.

Get-VMHost -Name <ESXi Host> | Get-VM | Move-VM -Datastore <NFS Datastore>

replace the <ESXi Host> and <NFS Datastore> with your values.

After the datastore move was completed I removed all the vms from inventory using vSphere Client.

Powershell

Using Powershell to add a NFS datastore to all ESXi hosts in a Datacenter

11. April 2012

Simple Script to add an NFS datastore to all hosts in a Datacenter.

First ensure you have created a credentials file that gives your script access to your vCenter. This stops you requiring to have your vcenter hostname/ipaddress, username and password written in your scripts. This can be done using the following script from a powerCLI cmd:

New-VICredentialStoreItem -Host xx.xx.xx.xx -User <youruser> -Password <yourpassword> -File “C:\Scripts\creds.crd”

Next use the following script. Check the User variables for your environment...

# User variables: adjusted for the environment
###################################
# Load VMWare add-ins
if (-not (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {
    Add-PSSnapin VMware.VimAutomation.Core
}
# Set location of credentials file
$credsFile = "C:\Scripts\creds.crd"
# import credentials file
$Creds = Get-VICredentialStoreItem -file $credsFile
# Datacenter name
$datacenterName = "myDatacenter"
# NFS Host IP
$nfsHost = "10.0.10.1"
# NFS share name
$nfsShare = "/nfs/Share"
# New datastore name
$nfsDatastore = "Share"

 

####################################################################################################################
# Start Of Execution
####################################################################################################################

#connect to vCenter using credentails supplied in credentials file
Connect-VIServer -Server $Creds.Host -User $Creds.User -Password $Creds.Password -WarningAction SilentlyContinue | Out-Null
echo "Connected to vCenter"

echo "starting addition of NFS share to ESXi Hosts"

foreach ($esx in get-datacenter -Name $datacenterName | get-VMhost | sort Name)
{
    $esx | New-Datastore -Nfs -Name $nfsDatastore -NFSHost $nfsHost -Path $nfsShare
    echo "NFS share added to $esx"
}

echo "Task completed"

Disconnect-VIServer -Server $Creds.Host -Force -Confirm:$False

To run this script simply run from either a powerCLI cmd or PowerShell cmd.

NFS, Powershell