Create datastore from Get-ScsiLUN output

I rebuild my environment often and I found myself looking for a programatic way to create datastores based on a volume name. After a fair amount of #fail I was able to get the following to work and thought I’d share in case anyone else was looking for something similar.

To start, both the volume name we are looking for as well as the canonical name of the device can be found using Get-ScsiLun:

$paths = Get-ScsiLun -vmhost "esxhostIP" | Get-ScsiLunPath -Name *desktop*

This gives me the following output (abridged):


To filter out just the volume name I want to use for the datastore, this did the trick:

$datastores = $ | foreach-object {$_.split(',')[1]} | foreach-object {$_.split('.')[4]} | get-unique

Similarly, the naa device name was generated as so:

$canonicalNames = $ | foreach-object {$_.split(',')[3]} | foreach-object {$_.split('-')[1]} | get-unique

The datastores can then be built using the following:

new-datastore -vmhost $vmhost -name $datastores[$i] -Path $canonicalNames[$i] -vmfs

Full sample script:

#Format datastores based on volume name

Connect-VIServer -Server view-vcenter.vdi.sf.local -User vdi\administrator -Password P@ssw0rd

$vmhost = "vdi1.vdi.sf.local"

#get a list of the paths available which will also show volume name and canonical (naa) device name

write-host "Getting list of paths available on $vmhost"

$paths = Get-ScsiLun -vmhost vdi1.vdi.sf.local | Get-ScsiLunPath -Name *desktop*

#from the paths, get a list of the unique volume names and naa devices

$datastores = $ | foreach-object {$_.split(',')[1]} | foreach-object {$_.split('.')[4]} | get-unique

$canonicalNames = $ | foreach-object {$_.split(',')[3]} | foreach-object {$_.split('-')[1]} | get-unique

#print out what pairings we are about to make

write-host "About to create the following datastore to canonical device pairings"

for ($i = 0; $i -lt $datastores.count; $i++) {

  write-host $datastores[$i] "<->" $canonicalNames[$i]


Read-host "Press Enter to continue or Ctrl-C to quit" | Out-Null

#Loop to create datastores matching $datastores[$i] to $canonicalNames[$i]

for ($i = 0; $i -lt $datastores.count; $i++) {

  write-host "Creating datastore" $datastores[$i] "on device" $canonicalNames[$i]

  new-datastore -vmhost $vmhost -name $datastores[$i] -path $canonicalNames[$i]


Write-Host "Done creating datastores" -ForegroundColor Green

write-host "Disconnecting from vCenter"

Disconnect-VIServer -Server * -Force -Confirm:$false

Hope some find it useful.


0 Kudos
1 Reply

Thanks for sharing this code.

A small tip. You can combine:

foreach-object {$_.split(',')[1]} | foreach-object {$_.split('.')[4]}


foreach-object {$_.split(',')[1].split('.')[4]}

Blog: | Twitter: @rvdnieuwendijk | Author of:
0 Kudos