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

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 = ""

# 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.