Script to Add Multiple NFS Datastores to an ESXi Host

I am sure I’m not the first admin that has needed to add an NFS datastore to multiple hosts, and usually it’s multiple datastores that are needed as well. Normally, I would go to each host, and add the storage manually via the vSphere Client.  But after doing this for quite some time, I decided I needed a better way to get this task done.  Scripting!

I have recently started to use PowerCLI to automate many of my daily tasks (Hint: more scripts to come) and decided to share the one I’ve used the most first.  The script takes an input after running, asking you to input your host name.  Inside the script, you will set the datastores you want to add to the host.  Those are the only changes that are needed when being run.  This script has saved me a great deal of man hours and some headaches.  A great advantage to scripting is that you avoid those sneaky spelling mistakes or clicking the wrong button.

The script is below here (The bold parts are what need to be changed by you):

$VMHost = (Read-Host “Please enter the name of your ESX Host you wish to configure”)

$shellObject = new-object -comobject wscript.shell
$intAnswer = $shellObject.popup(“Do you want to add the datastores?”, 0,”Add datastores – remember you must have added the hosts on the storage”,4)
If ($intAnswer -eq 6) {
Write “Creating Datastores on $VMHost…”
New-Datastore -Nfs -VMHost $VMHost -Name DatastoreName1 -Path /vol/DatastoreName1 -NfsHost 192.168.255.251
New-Datastore -Nfs -VMHost $VMHost -Name DatastoreName2 -Path /vol/DatastoreName2 -NfsHost 192.168.255.251
New-Datastore -Nfs -VMHost $VMHost -Name DatastoreName3 -Path /vol/DatastoreName3 -NfsHost 192.168.255.251
} else {
Write “Skipping Datastores on $VMHost…”
}

When running the script, you will see the following output asking you to put in your hostname:

addnfsdatastore

You will then see a successful message for each datastore added to the host. You must remember to add the host to the NFS Export share on the storage itself before completing this step.

Script courtesy of VMware PowerCLI Blog

4 Replies to “Script to Add Multiple NFS Datastores to an ESXi Host”

    • I don’t. Since I only used this for a couple hosts, didn’t add that as part of it.

      Glad it worked well for you!

  1. I get an error running the script. Help please!

    Missing ‘)’ in method call.
    At C:\PowerCLI 5.1 r2\Scripts\addnfsdatastores.ps1:4 char:34
    + $intAnswer = $shellObject.popup( <<<< Do you want to add the datastores?, 0,
    â??Add datastores â?" remember you must have added the hosts on the storageâ??,
    4)
    + CategoryInfo : ParserError: (CloseParenToken:TokenId) [], Parse
    Exception
    + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall

    • Looks like you didn’t copy it right.

      Put it in a syntax editor and you should see where your missing ‘)’ is.