PowerCLI

 View Only
  • 1.  foreach-object

    Posted Sep 07, 2009 10:28 AM

    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.



  • 2.  RE: foreach-object

    Posted Sep 07, 2009 10:35 AM

    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)
    }
    
    



  • 3.  RE: foreach-object

    Posted Sep 08, 2009 06:57 AM

    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??



  • 4.  RE: foreach-object
    Best Answer

    Posted Sep 08, 2009 08:41 AM

    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
    
    



  • 5.  RE: foreach-object

    Posted Sep 09, 2009 03:34 AM

    Excellent, thanks for your help.