PowerShell to Rename Datastores

At work we recently had a health check performed on our virtual environment. When the results came back, and I noticed a trend with our legacy VM hosts. Particularly where we didn’t follow the same standards as we did on the newer hosts. The issue I’ll be talking about, is renaming the local datastores. So now is the time to apply the same standards across the entire environment.

In this post, I’m going to show how to use PowerShell to change the name of the datastores for my environment. The datastores that were flagged by the health check were the local datastores with names that started with “datastore1”.

$datastoreNames = get-datastore datastore1*

The snippit above generates a list of the datastores with the name that starts with “datastore1”. When I ran this, it generated a list of 16 datastores that name started with datastore1.

datastore1 (12)
datastore1 (6)
datastore1
datastore1 (8)
datastore1 (3)
datastore1 (21)
datastore1 (2)
datastore1 (1)
datastore1 (5)
datastore1 (23)
datastore1 (11)
datastore1 (9)
datastore1 (13)
datastore1 (4)
datastore1 (7)
datastore1 (20)

This is just a start of how I’m going to correct the datastore names, but now I need to know which datastore goes with which host. Our standard is to name the local datastore, vmhostname-localstorage. So I need to see if there is a properties for the datastore that can point me into the correct host. Digging into the ExtensionData property I was able to find the information.

$datastoreNames = get-datastore datastore1*
foreach ($Datastore in $datastoreNames){
    write-host $Datastore.name "- " -NoNewline 
    $VMhostFQDN = (get-vmhost -id $(get-datastore $datastore).ExtensionData.host.key).name
}

This gathers VMhost ID from a property under the datastore cmdlet. I can now put that into the Get-VMhost cmdlet to get the VMhost’s name. We use the FQDN name for our hosts, so now the name will need to be split to remove the domain name. Then we can append “-localstorage”.

$VMhostname = $VMhostFQDN.Split(".")[0]
$datastorenewname = $VMhostname + "-localstorage"

So now once all of the parts are put together, this will rename the local datastore for the VMhost based on the it’s name.

$datastoreNames = get-datastore datastore1*
foreach ($Datastore in $datastoreNames){
    write-host $Datastore.name "- " -NoNewline 
    $VMhostFQDN = (get-vmhost -id $(get-datastore $datastore).ExtensionData.host.key).name
    $VMhostname = $VMhostFQDN.Split(".")[0]
    $datastorenewname = $VMhostname + "-localstorage"
    Get-datastore -name $datastore | Set-datastore -Name $datastorenewname
}

Now with all of the local datastores following the same standard, I can work on the next part of the health check that needs resolved.

-Stuart

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.