ranjitcool
Hot Shot
Hot Shot

Basics issue

Hey Guys,

I am trying to learn powervcli.

I downloaded powergui and am writing a very basic script.


$var = Get-Content c:\temp\servers.txt
foreach($var in var){
get-vm

}

In the servers.txt i have an ip address.

Please feel free to make fun of my basic program Smiley Happy

Thanks

RJ

Please award points if you find my answers helpful Thanks RJ Visit www.rjapproves.com
0 Kudos
4 Replies
pH2
Contributor
Contributor

Not sure what you are trying to do, but how about...

C:\temp\servers.txt >>

server1

server2

server3

$hosts = Get-Content C:\temp\servers.txt
foreach($vm in $hosts)
{
     Get-VM $vm
}
~pH2
0 Kudos
RvdNieuwendijk
Leadership
Leadership

As PH2 stated it will be easier to have the VM names in the text file instead of the IP addresses. In that case I would change your script into:

$vms = Get-Content c:\temp\servers.txt
foreach($vm in $vms){
  get-vm -Name $vm

}

I always try to give a variable a name that makes clear what the content is. If you have only one variable in your script it is no problem. But when you start to write larger scripts with many variables, your script will be much easier to read if you use good variable names.

In your version of the script the line

foreach($var in var){


is missing a $ sign before the second variable. And the first and second variable names should be different.

The line

get-vm


is missing the Name parameter. And thus it would return all the VM's in your environment.

I hope you learned something from this answer.

Regards, Robert

Blog: https://rvdnieuwendijk.com/ | Twitter: @rvdnieuwendijk | Author of: https://www.packtpub.com/virtualization-and-cloud/learning-powercli-second-edition
0 Kudos
RvdNieuwendijk
Leadership
Leadership

Welcome to the VMware Communities.

Your script will work as expected. But the term hosts is normally used for ESX(i) servers. This makes reading your script a bit confusing. That is why I changed that variable to $vms in my script in the previous post.

It is also possible to use the pipeline. This will change the script into an oneliner:

Get-Content C:\temp\servers.txt | ForEach-Object { Get-VM -Name $_ }
Blog: https://rvdnieuwendijk.com/ | Twitter: @rvdnieuwendijk | Author of: https://www.packtpub.com/virtualization-and-cloud/learning-powercli-second-edition
0 Kudos
pH2
Contributor
Contributor

Appreciate the welcome.

I completely agree, thanks for clarifying the simple mistake in the original post.

~pH2
0 Kudos