Can someone point me in the right direction? I'm trying to input a list of VMs from a text file to a simple script (example below), but can't get the loop working. You can tell I'm new to Powershell (and only have basic scripting knowledge)!
$vms = import-csv "D:\virtualisation\scripts\powershell\vms.txt"
foreach ($vm in $vms) {
get-datastore -vm $vm
}
I've also tried the get-content cmdlet, with similar results.
You could change that line as follows
$VMs = Import-Csv "D:\virtualisation\scripts\powershell\vms.txt" | %{get-vm $_.Name} | sort Name
But if the CSV file only contains the names of the VMs in a specific cluster you could indeed also use this line
$VMs = Get-Cluster <your-cluster-name> | Get-Vm | Sort Name
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Can you also give us a sample of what you have in the file "vms.txt" ?
If that file is a real CSV file with row headers the name of your vm should be in a property of the $vm variable.
For example, if the " vms.txt" contains something like this
Name,Attribute PC1,abcd PC2,klmn
Your code should be
$vms = import-csv "D:\virtualisation\scripts\powershell\vms.txt" foreach ($vm in $vms) { get-datastore -vm (Get-Vm $vm.Name) }
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Great, thanks. The text file just had a list of VM names:
Name
PC1
PC2
Trying to make sense of a VM disk size script I downloaded (attached). Can you tell me how to apply your earlier advice to replace the line below, so as to take input from my text file - everything I have tried has failed (typically getting "attempted to divide by zero"):
$VMs = Get-VM | Sort Name # Get all VMs (sorted)
Or would it just be easier to add a Get-Cluster statement and filter the output for the VMs I'm interested in??
You could change that line as follows
$VMs = Import-Csv "D:\virtualisation\scripts\powershell\vms.txt" | %{get-vm $_.Name} | sort Name
But if the CSV file only contains the names of the VMs in a specific cluster you could indeed also use this line
$VMs = Get-Cluster <your-cluster-name> | Get-Vm | Sort Name
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Excellent, thanks for your help.