Hi everyone, I am new to scripting. I am trying to script adding disks to different datastores on different hosts (not clustered). Lets say I have VMs called VM1 and VM2 I get this info from adddisk.txt file. I want to add disks to those VMs but I don't know the datastore name under specific host. If VM1 is under Host1, then datastore name is : Datastore1 IF VM2 is under Host2, then datastore name is : Datastore2 So how can I add disks to multiple VMs without knowing the datastore name? $servers = Get-Content "C:\Scripts\AddDisk\adddisk.txt" New-HardDisk -VM $servers -CapacityGB 30 -DiskType Flat -Datastore "DatasoreName" -StorageFormat Thin Thanks in advance.
Try like this
Get-Contentt c:\Script\adddisk.txt | %{
$hostname = Get-VM -Name $_ | Get-VMHost | Select -ExpandProperty Name
if($hostname -eq "esx3"){
$dsname = "Datastore3"
}
elseif($hostname -eq "esx4"){
$dsname = "Datastore4"
}
New-HardDisk -VM $_ -CapacityGB 5 -DiskType Flat -Datastore $dsname -StorageFormat Thin
}
The Get-Content will read the file line by line.
We execute the codeblock for each line (the ForEach construct - the alias is %)
Testing on equality of strings is done with the -eq operator, the = operator is only used for assignments.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
You can find the host a VM is on like this
$hostname = Get-VM -Name $vmName | Get-VMHost | Select -ExpandProperty Name
You can now test on te hostname
if($hostname -like "*1$"){
$dsname = "datastore1"
}
elseif($hostname -like "*2$"){
$dsname = "datastore2"
}
There are of course many other ways to accomplish the same, but this is in my opinion one of the most simple ones.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Hi LucD, thanks for your reply. according to your reply I have updated the script. Now looks like this. Please see attached jpeg.
Sorry to ask here cause I am really new to scripting.
If I have 4 VMs here.
VM1 and VM2 on ESX3
VM3 and VM4 on ESX4
This script adds new disk to VM1 and VM2 but not adding on VM3 and VM4. Error message says Invalid configuration for device "0"
Can you spot why?
Thanks a lot.
What exactly do you have in the adddisk.txt file ?
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
addisk.txt contains VM1 VM2 VM3 VM4
Try like this
Get-Contentt c:\Script\adddisk.txt | %{
$hostname = Get-VM -Name $_ | Get-VMHost | Select -ExpandProperty Name
if($hostname -eq "esx3"){
$dsname = "Datastore3"
}
elseif($hostname -eq "esx4"){
$dsname = "Datastore4"
}
New-HardDisk -VM $_ -CapacityGB 5 -DiskType Flat -Datastore $dsname -StorageFormat Thin
}
The Get-Content will read the file line by line.
We execute the codeblock for each line (the ForEach construct - the alias is %)
Testing on equality of strings is done with the -eq operator, the = operator is only used for assignments.
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
You are the master LucD!! Thanks a lot mate.
